1

Suppose there is a array..and the contents of the array="ironman" Now, i need to add some additional character to this string like "i*r%o#n@m^a!n"

out[i]="ironman"

Outputs: 
out[]=i
out[]=*
out[]=r
out[]=%
out[]=o
out[]=#
out[]=n
out[]=@
out[]=m
out[]=^
out[]=a
out[]=!
out[]=n

I have written a code which concatenate at the end of the string, but i want to concatenate between the string.

char in[20] = "ironman";
const unsigned int symbol_size = 5;
std::string symbols[symbol_size];
std::string out(in);
out = out + "@" + "*" + "#";
2
  • 2
    Use insert to insert characters. Commented May 7, 2015 at 17:01
  • take count of both strings, make a new array and fetch a character from each string copy to new array Commented May 7, 2015 at 17:03

2 Answers 2

1

You can use string.insert(pos, newString). Example below:

std::string mystr
mystr.insert(6,str2); 

If you know the index, specify it directly as 'pos'. Otherwise, you may want to do somekind of str.find() and pass in the result.

Sign up to request clarification or add additional context in comments.

Comments

1

If I have understood correctly what you need then you can use the following straightforward approach

#include <iostream>
#include <string>
#include <cstring>

int main()
{
    char in[] = "ironman";
    char symbols[] = "*%#@^!";

    std::string s;
    s.reserve( std::strlen( in ) + std::strlen( symbols ) );

    char *p = in;
    char *q = symbols;

    while ( *p && *q )
    {
        s.push_back( *p++ );
        s.push_back( *q++ );        
    }

    while ( *p ) s.push_back( *p++ );
    while ( *q ) s.push_back( *q++ );

    std::cout << s << std::endl; 
}   

The program output is

i*r%o#n@m^a!n

You can write a separate function. For example

#include <iostream>
#include <string>
#include <cstring>

std::string interchange_merge( const char *s1, const char *s2 )
{
    std::string result;
    result.reserve( std::strlen( s1 ) + std::strlen( s2 ) );

    while ( *s1 && *s2 )
    {
        result.push_back( *s1++ );
        result.push_back( *s2++ );      
    }

    while ( *s1 ) result.push_back( *s1++ );
    while ( *s2 ) result.push_back( *s2++ );

    return result;
}

int main()
{
    char in[] = "ironman";
    char symbols[] = "*%#@^!";

    std::string s = interchange_merge( in, symbols );

    std::cout << s << std::endl; 
}   

The output will be the same as above

i*r%o#n@m^a!n

1 Comment

Thank you..i appreciate your kind help !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.