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.
C program to concatenate two strings
The program has undefined behavior because you did not allocate memory for entered strings.
char *s=(char *)malloc(sizeof(char *));
char *s2=(char *)malloc(sizeof(char *));
fgets(s,10,stdin);
fgets(s2,10,stdin);
You only allocated memory for two pointers ( sizeof(char *)
).
You need to allocate memory large enough that can contains entered strings and their concatenation in the first character array.
The function fgets
can append the new line character '\n' to an entered string. You need to overwrite it.
Also you should not change the original pointers because you need to use them to free the allocated memory.
And take into account that the result string will contain at least 11
characters including the terminating zero character '\0'
instead of 10
characters if you are going to enter "hello"
and "world"
and concatenate them. Though in general it is better to reserve 13
characters if the entered strings will not contain the new line character.
The program can look for example the following way
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
enum { N = 7 };
char *s1 = malloc( 2 * N - 1 );
char *s2 = malloc( N );
s1[0] = '\0';
s2[0] = '\0';
fgets( s1, N, stdin );
fgets( s2, N, stdin );
char *p1 = s1;
while (*p1 != '\n' && *p1 != '\0') ++p1;
for (char *p2 = s2; *p2 != '\n' && *p2 != '\0'; ++p2)
{
*p1++ = *p2;
}
*p1 = '\0';
puts( s1 );
free( s1 );
free( s2 );
}
The program output might be
hello
world
helloworld
Instead of these lines
char *s1 = malloc( 2 * N - 1 );
char *s2 = malloc( N );
s1[0] = '\0';
s2[0] = '\0';
you could write
char *s1 = calloc( 2 * N - 1, sizeof( char ) );
char *s2 = calloc( N, sizeof( char ) );
The arrays are zero initialized to keep empty strings in case when calls of fgets will be interrupted.
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 to concatenate two strings and save in third variable in C?
The problem is that you are [str]concatenating to an array (header
) which doesn't extra space (C arrays can't be changed in size).
snprintf
could be a better fit here.
If you know the maximum possible length of strDevicename
, you could use a fixed size buffer:
const char header[] = "POST /api/add HTTP/1.1\r\nHost: xxxxxxx:3000\r\nContent-Type: application/octet-stream; charset=utf-8\r\nContent-Length: 500\r\nName: ";
const char tail[] = "\r\n\r\n";
char buf[(sizeof header - 1) + MAX_DEV_LENGTH + (sizeof tail - 1) + 1];
/* sizeof would count the null byte in header & tail arrays. */
snprintf(buf, sizeof buf, "%s%s%s", header, strDevicename, tail);
If strDevicename
is of unknown length, you could use asprintf
(GNU function):
char *buf = NULL;
if (asprintf(&buf, "%s%s%s", header, strDevicename, tail) == -1) {
/* handle memory allocation failure */
}
...
free(buf);
If you asprintf
isn't available, then you could allocate sufficient memory (just as above) yourself using malloc
and then use snprintf
.
Concatenate two strings without using strcat
char *myconcat(const char *s1, const char *s2)
{
size_t len1,len2;
char *result = malloc((len1 = strlen(s1)) + (len2 = strlen(s2)) + 1);
if(result)
{
memcpy(result, s1, len1);
memcpy(result + len1, s2, len2 + 1);
}
return result;
}
C program to concatenate two pointer strings with functions
There are a number of problems with your concaten
function.
First, it should be returning a char*
pointer, not a char
; thus, the declaration should look like this:
char* concaten(const char* str1, const char* str2);
Next, the function will need to allocate memory in which to store the concatenated strings; this can be done with the malloc()
function, and the number of characters required will be the sum of the lengths of the two input strings plus one, for the required nul
-terminator.
Third, the logic of your two loops is wrong. You are incrementing i
and j
twice per loop but not incrementing either of the source pointers.
Finally, you must add a nul
-terminator at the end of your new string.
Here's a version with the above fixes applied:
char* concaten(const char* str1, const char* str2)
{
int i = 0, j = 0;
char* result = malloc(strlen(str1) + strlen(str2) + 1); // allow space for nul-terminator
while (*str1) {
result[i++] = *str1++; // Only increment i once and "str1" once
}
while (*str2) {
result[i + j++] = *str2++; // Only increment j once and "str2" once
}
result[i + j] = '\0'; // Add required nul-terminator
return result;
}
Also, as you have allocated memory (with the malloc
call), you should release that when you're done with the data, using a call to free
. Here's how your main
might work:
int main(void)
{
char* answer = concaten("Code", "blocks");
printf("%s", answer);
free(answer);
return 0;
}
Note: You can also remove the j
variable entirely, and just re-use the result[i++]
expression in the second loop. I've left it in so that you can more easily relate my code to your own.
Concatenate two strings using memcpy
You have to ensure that str1
points to a memory location big enough to receive the entire result :
char *concat(char const*str1, char const*str2) {
size_t const l1 = strlen(str1) ;
size_t const l2 = strlen(str2) ;
char* result = malloc(l1 + l2 + 1);
if(!result) return result;
memcpy(result, str1, l1) ;
memcpy(result + l1, str2, l2 + 1);
return result;
}
Additionally, you should add error checking, as much as possible, at least some assert(str1) ; assert(str2) ;
...
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
Hope that helps.
Related Topics
How to Get Console Output in C++ With a Windows Program
How to Set Up Google C++ Testing Framework (Gtest) With Visual Studio 2005
How to Convert a String Variable Containing Time to Time_T Type in C++
Why Does C++ Need a Separate Header File
Embed Text File in a Resource in a Native Windows Application
Same Random Numbers Every Loop Iteration
How to Parse a Url in C++ Cross Platform
How to Remove an Item from a Stl Vector With a Certain Value
In C++ How to Go to a Specific Line in a Text File
Why Should I Declare a Virtual Destructor For an Abstract Class in C++
High Resolution Timer With C++ and Linux
How to Concatenate Multiple C++ Strings on One Line
Msvc++ Variadic Macro Expansion
C++ Vector Size. Why -1 Is Greater Than Zero
What's the Right Way to Overload Operator== for a Class Hierarchy