Strings combination

Jul 16, 2008 at 1:16am
In this content, s1, s2 and s3 are strings

If I wanna combine s1 and s2 into s3. Is there any related code that can used from library?

The string S3 should be like S3[S1+S2]
Jul 16, 2008 at 1:30am
Last edited on Jul 16, 2008 at 1:32am
Jul 16, 2008 at 4:13am
you can try the srtcat command. it concatenates two strings and would result in an output just like the kind you want.
hope this helps
Jul 16, 2008 at 8:24am
or sprintf which will do it in one go
1
2
3
4
strcpy(s3, s1);
strcat(s3, s2);
// or sprintf
sprintf(s3,"%s%s", s1, s2);


or use std::string http://www.cplusplus.com/reference/string/string/

1
2
3
std::string s3(s1);

s3.append(s2);


Hope this helps
Last edited on Jul 16, 2008 at 8:25am
Jul 16, 2008 at 7:09pm
In this content, s1, s2 and s3 are strings


1
2
3
string s1 = "string two ";
string s2 = "string one";
string s3 = s1 + s2;
Jul 16, 2008 at 7:26pm
@Zaita

That really works? =O

My god it does. So then whats the point of all of these other ways to do it?
Last edited on Jul 16, 2008 at 7:29pm
Jul 16, 2008 at 8:20pm
strcpy, strcat and printf are inherited from C.

s3.append() is more useful when appending char[] or char* to a string. It has issues when you do something like string s = string + char[] + char[] + string + etc. I typically do string s = string + string(char[]) + etc. But .append() works too :)
Jul 16, 2008 at 8:22pm
s1 + s2
is just a pretty way of writing
s1.append(s2),
which internally does something like
1
2
s1.reserve( s1.length() + s2.length() );
char_traits <char> ::copy( s1.internal_data +s1.length(), s1.internal_data, s2.length() );


[edit] too slow... :-)
Last edited on Jul 16, 2008 at 8:22pm
Topic archived. No new replies allowed.