Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to write long strings in Multi-lines C/C++?
To write long strings in multi-lines, you can use the 'newline character' or 'string concatenation'. It increases the readability of the code, makes the code look clean, and you can avoid horizontal scrolling.
In this article, we have a long string and our task is to write the long string in multi-lines in C.
Syntax
// Using newline character
char str[] = "First line\nSecond line\nThird line";
// Using string concatenation
char str[] = "First part of string "
"Second part of string "
"Third part of string";
Method 1: Using Newline Character
In this approach, we use the newline character (\n) to write the long string into multiple lines. The newline character (\n) inserts a line break that breaks the long string into multiple lines when printed −
#include <stdio.h>
int main() {
char longString[] = "This is a very long string.\n"
"It will be distributed in\n"
"multiple lines. Say Hello world!";
printf("%s\n", longString);
return 0;
}
This is a very long string. It will be distributed in multiple lines. Say Hello world!
Method 2: Using String Concatenation
In C, adjacent string literals are automatically concatenated by the compiler. This allows you to break long strings across multiple lines for better readability without adding newlines to the actual string content −
#include <stdio.h>
int main() {
char longString[] = "This is a very long string "
"that will be concatenated "
"into a single line. Hello world!";
printf("%s\n", longString);
return 0;
}
This is a very long string that will be concatenated into a single line. Hello world!
Method 3: Using Backslash Continuation
You can also use a backslash (\) at the end of a line to continue the string on the next line. This creates a single string without line breaks −
#include <stdio.h>
int main() {
char longString[] = "This is a very long string \
that continues on the next line \
and forms a single string.";
printf("%s\n", longString);
return 0;
}
This is a very long string that continues on the next line and forms a single string.
Key Points
- Newline character (\n): Creates actual line breaks in the output
- String concatenation: Combines adjacent string literals into one string
- Backslash continuation: Continues the same string on the next line
- Choose the method based on whether you want line breaks in the output or not
Conclusion
C provides multiple ways to handle long strings across multiple lines. Use newline characters for multi-line output, string concatenation for single-line output with better code readability, or backslash continuation for simple line breaks in source code.
