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 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 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 to add two strings?
In this expression
a+b
the array designators are implicitly converted to pointers to the first characters of the strings. So in fact you are trying to add two pointers of type char *
.
From the C Standard (6.3.2.1 Lvalues, arrays, and function designators)
3 Except when it is the operand of the sizeof operator or the unary &
operator, or is a string literal used to initialize an array, an
expression that has type ‘‘array of type’’ is converted to an
expression with type ‘‘pointer to type’’ that points to the initial
element of the array object and is not an lvalue. If the array object
has register storage class, the behavior is undefined.
However operator +
is not defined for pointers in C and C++.
If you indeed want to add two strings then the result of the operation will be a third string that contains the first two strings.
There are two approaches. Either you declare a third character array large enough to contain the first two strings. Or you need to allocate dynamically memory for the resulted string.
For example
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main( void )
{
char a[] = "My name is";
char b[] = "kamran";
char c[sizeof( a ) + sizeof( b )];
strcpy( c, a );
strcat( c, " " );
strcat( c, b );
puts( c );
char *d = malloc( sizeof( a ) + sizeof( b ) );
if ( d )
{
strcpy( d, a );
strcat( d, " " );
strcat( d, b );
puts( d );
}
free( d );
}
The program output is
My name is kamran
My name is kamran
How to combine two strings i Haskell and return a new string
combine = zipWith (++)
zipWith takes two lists, and applies the function given to the first item of both lists, then the second, etc. If one list is longer than the other, its extra items will be skipped.
The ++
function takes two lists and joins them together. A string is just a list of characters.
"hello " ++ "world" == "hello world"
usage:
λ> combine ["me","you","he"] ["she","they","it"]
["meshe","youthey","heit"]
λ> combine [] []
[]
λ> combine ["me", "you"] ["she"]
["meshe"]
λ>
The ++
operator is very basic though, so you might be better continuing reading whatever learning material you're using before coming to stackoverflow, as you'll have a lot of questions which I expect will be answered in your book.
If you don't want to use zipWith, you can write it very simply with recursion like so:
combine [] _ = []
combine _ [] = []
combine (x:xs) (y:ys) = (x ++ y) : combine xs ys
Usage is the same as before.
What is the best way to add two strings together?
You are always going to create a new string whe concatenating two or more strings together. This is not necessarily 'bad', but it can have performance implications in certain scenarios (like thousands/millions of concatenations in a tight loop). I am not a PHP guy, so I can't give you any advice on the semantics of the different ways of concatenating strings, but for a single string concatenation (or just a few), just make it readable. You are not going to see a performance hit from a low number of them.
How to concatenate two string in Dart?
There are 3 ways to concatenate strings
String a = 'a';
String b = 'b';
var c1 = a + b; // + operator
var c2 = '$a$b'; // string interpolation
var c3 = 'a' 'b'; // string literals separated only by whitespace are concatenated automatically
var c4 = 'abcdefgh abcdefgh abcdefgh abcdefgh'
'abcdefgh abcdefgh abcdefgh abcdefgh';
Usually string interpolation is preferred over the +
operator.
There is also StringBuffer for more complex and performant string building.
Related Topics
Download of .Zip File Runs a Corrupted File PHP
Uploading a File via Ajax with PHP
Submit Multiple Forms with One Button
PHP Prepared Statement Problems
What Does a Leading Zero Do for a PHP Int
How to Deploy Correctly When Using Composer's Develop/Production Switch
What Is Sapi and When Would You Use It
PHP Warning: Unknown: Failed to Open Stream
PHP Date Time Greater Than Today
How to Test PHP Locally Without Installing a Server