Wednesday, January 22, 2025
HomeProgrammingHow do I concatenate const/literal strings in C?

How do I concatenate const/literal strings in C?

You can concatenate constant/literal strings in C by:

Directly placing them together: When two string literals are placed adjacent to each other, the compiler automatically concatenates them into a single string. For example:

C

const char* message = “Hello” “World”;

This will create a single string HelloWorld.

Using the sprintf() function: This function formats and prints data to a character array. You can use it to concatenate strings by specifying the format specifier %s for each string. For example:

See also  How Can I Clear the Interpreter Console in Python?

C

char result[50];

sprintf(result, “%s%s”, “Hello”, “World”);

This will store the concatenated string “HelloWorld” in the result array.

Using the strcat() function: This function appends a copy of one string to the end of another string. However, you must ensure that the destination string has enough space to accommodate the concatenated result. For example:

See also  What are signals in the C programming language?

C

char result[50] = “Hello”;

strcat(result, “World”);

This will modify the result array to contain “HelloWorld”.

Remember that string literals in C are immutable, meaning their contents cannot be changed after they are created. Therefore, methods like direct modification of the string pointer are not allowed.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x