简体   繁体   中英

How to concatenate additional character to a string in c++

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 + "@" + "*" + "#";

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM