How Can Strings Be Concatenated

How do I concatenate const/literal strings in C?

In C, "strings" are just plain char arrays. Therefore, you can't directly concatenate them with other "strings".

You can use the strcat function, which appends the string pointed to by src to the end of the string pointed to by dest:

char *strcat(char *dest, const char *src);

Here is an example from cplusplus.com:

char str[80];
strcpy(str, "these ");
strcat(str, "strings ");
strcat(str, "are ");
strcat(str, "concatenated.");

For the first parameter, you need to provide the destination buffer itself. The destination buffer must be a char array buffer. E.g.: char buffer[1024];

Make sure that the first parameter has enough space to store what you're trying to copy into it. If available to you, it is safer to use functions like: strcpy_s and strcat_s where you explicitly have to specify the size of the destination buffer.

Note: A string literal cannot be used as a buffer, since it is a constant. Thus, you always have to allocate a char array for the buffer.

The return value of strcat can simply be ignored, it merely returns the same pointer as was passed in as the first argument. It is there for convenience, and allows you to chain the calls into one line of code:

strcat(strcat(str, foo), bar);

So your problem could be solved as follows:

char *foo = "foo";
char *bar = "bar";
char str[80];
strcpy(str, "TEXT ");
strcat(str, foo);
strcat(str, bar);

How do I concatenate two strings in C?

C does not have the support for strings that some other languages have. A string in C is just a pointer to an array of char that is terminated by the first null character. There is no string concatenation operator in C.

Use strcat to concatenate two strings. You could use the following function to do it:

#include <stdlib.h>
#include <string.h>

char* concat(const char *s1, const char *s2)
{
char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, s1);
strcat(result, s2);
return result;
}

This is not the fastest way to do this, but you shouldn't be worrying about that now. Note that the function returns a block of heap allocated memory to the caller and passes on ownership of that memory. It is the responsibility of the caller to free the memory when it is no longer needed.

Call the function like this:

char* s = concat("derp", "herp");
// do things with s
free(s); // deallocate the string

If you did happen to be bothered by performance then you would want to avoid repeatedly scanning the input buffers looking for the null-terminator.

char* concat(const char *s1, const char *s2)
{
const size_t len1 = strlen(s1);
const size_t len2 = strlen(s2);
char *result = malloc(len1 + len2 + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
memcpy(result, s1, len1);
memcpy(result + len1, s2, len2 + 1); // +1 to copy the null-terminator
return result;
}

If you are planning to do a lot of work with strings then you may be better off using a different language that has first class support for strings.

How do I concatenate two strings in Java?

You can concatenate Strings using the + operator:

System.out.println("Your number is " + theNumber + "!");

theNumber is implicitly converted to the String "42".

How do I concatenate strings?

When you concatenate strings, you need to allocate memory to store the result. The easiest to start with is String and &str:

fn main() {
let mut owned_string: String = "hello ".to_owned();
let borrowed_string: &str = "world";

owned_string.push_str(borrowed_string);
println!("{}", owned_string);
}

Here, we have an owned string that we can mutate. This is efficient as it potentially allows us to reuse the memory allocation. There's a similar case for String and String, as &String can be dereferenced as &str.

fn main() {
let mut owned_string: String = "hello ".to_owned();
let another_owned_string: String = "world".to_owned();

owned_string.push_str(&another_owned_string);
println!("{}", owned_string);
}

After this, another_owned_string is untouched (note no mut qualifier). There's another variant that consumes the String but doesn't require it to be mutable. This is an implementation of the Add trait that takes a String as the left-hand side and a &str as the right-hand side:

fn main() {
let owned_string: String = "hello ".to_owned();
let borrowed_string: &str = "world";

let new_owned_string = owned_string + borrowed_string;
println!("{}", new_owned_string);
}

Note that owned_string is no longer accessible after the call to +.

What if we wanted to produce a new string, leaving both untouched? The simplest way is to use format!:

fn main() {
let borrowed_string: &str = "hello ";
let another_borrowed_string: &str = "world";

let together = format!("{}{}", borrowed_string, another_borrowed_string);

// After https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html
// let together = format!("{borrowed_string}{another_borrowed_string}");

println!("{}", together);
}

Note that both input variables are immutable, so we know that they aren't touched. If we wanted to do the same thing for any combination of String, we can use the fact that String also can be formatted:

fn main() {
let owned_string: String = "hello ".to_owned();
let another_owned_string: String = "world".to_owned();

let together = format!("{}{}", owned_string, another_owned_string);

// After https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html
// let together = format!("{owned_string}{another_owned_string}");
println!("{}", together);
}

You don't have to use format! though. You can clone one string and append the other string to the new string:

fn main() {
let owned_string: String = "hello ".to_owned();
let borrowed_string: &str = "world";

let together = owned_string.clone() + borrowed_string;
println!("{}", together);
}

Note - all of the type specification I did is redundant - the compiler can infer all the types in play here. I added them simply to be clear to people new to Rust, as I expect this question to be popular with that group!

How can strings be concatenated?

The easiest way would be

Section = 'Sec_' + Section

But for efficiency, see: https://waymoot.org/home/python_string/

How to concatenate two strings in C++?

First of all, don't use char* or char[N]. Use std::string, then everything else becomes so easy!

Examples,

std::string s = "Hello";
std::string greet = s + " World"; //concatenation easy!

Easy, isn't it?

Now if you need char const * for some reason, such as when you want to pass to some function, then you can do this:

some_c_api(s.c_str(), s.size()); 

assuming this function is declared as:

some_c_api(char const *input, size_t length);

Explore std::string yourself starting from here:

  • Documentation of std::string

How Java do the string concatenation using +?

No. It's not the same using StringBuilder than doing "a" + "b".

In Java, String instances are immutable.

So, if you do:

String c = "a" + "b";

You are creating new Strings every time you concatenate.

On the other hand, StringBuilder is like a buffer that can grow as it needs when appending new Strings.

StringBuilder c = new StringBuilder();
c.append("a");
c.append("b"); // c is only created once and appended "a" and "b".

Rule of the thumb is (changed thanks to the comments I got):

If you are going to concatenate a lot (i.e., concatenate inside a loop, or generating a big XML formed by several string concatenated variables), do use StringBuilder. Otherwise, simple concatenation (using + operator) will be just fine.

Compiler optimizations also play a huge role when compiling this kind of code.

Here'sfurther explanation on the topic.

And more StackOVerflow questions on the issue:

Is it better to reuse a StringBuilder in a loop?

What's the best way to build a string of delimited items in Java?

StringBuilder vs String concatenation in toString() in Java

String concatenation: concat() vs + operator

No, not quite.

Firstly, there's a slight difference in semantics. If a is null, then a.concat(b) throws a NullPointerException but a+=b will treat the original value of a as if it were null. Furthermore, the concat() method only accepts String values while the + operator will silently convert the argument to a String (using the toString() method for objects). So the concat() method is more strict in what it accepts.

To look under the hood, write a simple class with a += b;

public class Concat {
String cat(String a, String b) {
a += b;
return a;
}
}

Now disassemble with javap -c (included in the Sun JDK). You should see a listing including:

java.lang.String cat(java.lang.String, java.lang.String);
Code:
0: new #2; //class java/lang/StringBuilder
3: dup
4: invokespecial #3; //Method java/lang/StringBuilder."<init>":()V
7: aload_1
8: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
11: aload_2
12: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
15: invokevirtual #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/ String;
18: astore_1
19: aload_1
20: areturn

So, a += b is the equivalent of

a = new StringBuilder()
.append(a)
.append(b)
.toString();

The concat method should be faster. However, with more strings the StringBuilder method wins, at least in terms of performance.

The source code of String and StringBuilder (and its package-private base class) is available in src.zip of the Sun JDK. You can see that you are building up a char array (resizing as necessary) and then throwing it away when you create the final String. In practice memory allocation is surprisingly fast.

Update: As Pawel Adamski notes, performance has changed in more recent HotSpot. javac still produces exactly the same code, but the bytecode compiler cheats. Simple testing entirely fails because the entire body of code is thrown away. Summing System.identityHashCode (not String.hashCode) shows the StringBuffer code has a slight advantage. Subject to change when the next update is released, or if you use a different JVM. From @lukaseder, a list of HotSpot JVM intrinsics.

How do I concatenate strings in Swift?

You can concatenate strings a number of ways:

let a = "Hello"
let b = "World"

let first = a + ", " + b
let second = "\(a), \(b)"

You could also do:

var c = "Hello"
c += ", World"

I'm sure there are more ways too.

Bit of description

let creates a constant. (sort of like an NSString). You can't change its value once you have set it. You can still add it to other things and create new variables though.

var creates a variable. (sort of like NSMutableString) so you can change the value of it. But this has been answered several times on Stack Overflow, (see difference between let and var).

Note

In reality let and var are very different from NSString and NSMutableString but it helps the analogy.



Related Topics



Leave a reply



Submit