How Can Two Strings Be Concatenated

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".

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 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.

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.

Most efficient way to concatenate Strings

String.concat is faster than the + operator if you are concatenating two strings... Although this can be fixed at any time and may even have been fixed in java 8 as far as I know.

The thing you missed in the first post you referenced is that the author is concatenating exactly two strings, and the fast methods are the ones where the size of the new character array is calculated in advance as str1.length() + str2.length(), so the underlying character array only needs to be allocated once.

Using StringBuilder() without specifying the final size, which is also how + works internally, will often need to do more allocations and copying of the underlying array.

If you need to concatenate a bunch of strings together, then you should use a StringBuilder. If it's practical, then precompute the final size so that the underlying array only needs to be allocated once.



Related Topics



Leave a reply



Submit