C - Strings - Tutorialspoint
Có thể bạn quan tâm
Strings in C
A string in C is a one-dimensional array of char type, with the last character in the array being a "null character" represented by '\0'. Thus, a string in C can be defined as a null-terminated sequence of char type values.
Creating a String in C
Let us create a string "Hello". It comprises five char values. In C, the literal representation of a char type uses single quote symbols such as 'H'. These five alphabets put inside single quotes, followed by a null character represented by '\0' are assigned to an array of char types. The size of the array is five characters plus the null character six.
Example
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};Initializing String Without Specifying Size
C lets you initialize an array without declaring the size, in which case the compiler automatically determines the array size.
Example
char greeting[] = {'H', 'e', 'l', 'l', 'o', '\0'};The array created in the memory can be schematically shown as follows −
If the string is not terminated by "\0", it results in unpredictable behavior.
Note: The length of the string doesnt include the null character. The library function strlen() returns the length of this string as 5.
Loop Through a String
You can loop through a string (character array) to access and manipulate each character of the string using the for loop or any other loop statements.
Example
In the following example, we are printing the characters of the string.
#include <stdio.h> #include <string.h> int main (){ char greeting[] = {'H', 'e', 'l', 'l', 'o', '\0'}; for (int i = 0; i < 5; i++) { printf("%c", greeting[i]); } return 0; }Output
It will produce the following output −
HelloPrinting a String (Using %s Format Specifier)
C provides a format specifier "%s" which is used to print a string when you're using functions like printf() or fprintf() functions.
Example
The "%s" specifier tells the function to iterate through the array, until it encounters the null terminator (\0) and printing each character. This effectively prints the entire string represented by the character array without having to use a loop.
#include <stdio.h> int main (){ char greeting[] = {'H', 'e', 'l', 'l', 'o', '\0'}; printf("Greeting message: %s\n", greeting ); return 0; }Output
It will produce the following output −
Greeting message: HelloYou can declare an oversized array and assign less number of characters, to which the C compiler has no issues. However, if the size is less than the characters in the initialization, you may get garbage values in the output.
char greeting[3] = {'H', 'e', 'l', 'l', 'o', '\0'}; printf("%s", greeting);Constructing a String using Double Quotes
Instead of constructing a char array of individual char values in single quotation marks, and using "\0" as the last element, C lets you construct a string by enclosing the characters within double quotation marks. This method of initializing a string is more convenient, as the compiler automatically adds "\0" as the last character.
Example
#include <stdio.h> int main() { // Creating string char greeting[] = "Hello World"; // Printing string printf("%s\n", greeting); return 0; }Output
It will produce the following output −
Hello WorldString Input Using scanf()
Declaring a null-terminated string causes difficulty if you want to ask the user to input a string. You can accept one character at a time to store in each subscript of an array, with the help of a for loop −
Syntax
for(i = 0; i < 6; i++){ scanf("%c", &greeting[i]); } greeting[i] = '\0';Example
In the following example, you can input a string using scanf() function, after inputting the specific characters (5 in the following example), we are assigning null ('\0') to terminate the string.
printf("Starting typing... "); for (i = 0; i < 5; i++) { scanf("%c", &greeting[i]); } // Assign NULL manually greeting[i] = '\0'; // Printing the string printf("Value of greeting: %s\n", greeting);Output
Run the code and check its output −
Starting typing... Hello Value of greeting: HelloExample
It is not possible to input "\0" (the null string) because it is a non-printable character. To overcome this, the "%s" format specifier is used in the scanf() statement −
#include <stdio.h> #include <string.h> int main (){ char greeting[10]; printf("Enter a string:\n"); scanf("%s", greeting); printf("You entered: \n"); printf("%s", greeting); return 0; }Output
Run the code and check its output −
Enter a string: Hello You entered: HelloNote: If the size of the array is less than the length of the input string, then it may result in situations such as garbage, data corruption, etc.
String Input with Whitespace
scanf("%s") reads characters until it encounters a whitespace (space, tab, newline, etc.) or EOF. So, if you try to input a string with multiple words (separated by whitespaces), then the C program would accept characters before the first whitespace as the input to the string.
Example
Take a look at the following example −
#include <stdio.h> #include <string.h> int main (){ char greeting[20]; printf("Enter a string:\n"); scanf("%s", greeting); printf("You entered: \n"); printf("%s", greeting); return 0; }Output
Run the code and check its output −
Enter a string: Hello World! You entered: HelloString Input Using gets() and fgets() Functions
To accept a string input with whitespaces in between, we should use the gets() function. It is called an unformatted console input function, defined in the "stdio.h" header file.
Example: String Input Using gets() Function
Take a look at the following example −
#include <stdio.h> #include <string.h> int main(){ char name[20]; printf("Enter a name:\n"); gets(name); printf("You entered: \n"); printf("%s", name); return 0; }Output
Run the code and check its output −
Enter a name: Sachin Tendulkar You entered: Sachin TendulkarIn newer versions of C, gets() has been deprecated. It is potentially a dangerous function because it doesnt perform bound checks and may result in buffer overflow.
Instead, it is advised to use the fgets() function.
fgets(char arr[], size, stream);The fgets() function can be used to accept input from any input stream, such as stdin (keyboard) or FILE (file stream).
Example: String Input Using fgets() Function
The following program uses fgets() and accepts multiword input from the user.
#include <stdio.h> #include <string.h> int main(){ char name[20]; printf("Enter a name:\n"); fgets(name, sizeof(name), stdin); printf("You entered: \n"); printf("%s", name); return 0; }Output
Run the code and check its output −
Enter a name: Virat Kohli You entered: Virat KohliExample: String Input Using scanf("%[^\n]s")
You may also use scanf("%[^\n]s") as an alternative. It reads the characters until a newline character ("\n") is encountered.
#include <stdio.h> #include <string.h> int main (){ char name[20]; printf("Enter a name: \n"); scanf("%[^\n]s", name); printf("You entered \n"); printf("%s", name); return 0; }Output
Run the code and check its output −
Enter a name: Zaheer Khan You entered Zaheer KhanPrinting String Using puts() and fputs() Functions
We have been using printf() function with %s specifier to print a string. We can also use puts() function (deprecated in C11 and C17 versions) or fputs() function as an alternative.
Example
Take a look at the following example −
#include <stdio.h> #include <string.h> int main (){ char name[20] = "Rakesh Sharma"; printf("With puts(): \n"); puts(name); printf("With fputs(): \n"); fputs(name, stdout); return 0; }Output
Run the code and check its output −
With puts(): Harbhajan Singh With fputs(): Harbhajan SinghTừ khóa » C Char
-
Working With Character (char) In C - OpenGenus IQ
-
Strings In C (With Examples) - Programiz
-
C Character Type - Learn C Programming From Scratch
-
What's Difference Between Char S[] And Char *s In C? - GeeksforGeeks
-
Unsigned Char In C With Examples - GeeksforGeeks
-
ASCII Table
-
Char In C
-
What Is Char ** In C? [duplicate] - Stack Overflow
-
C Programming Tutorial 25 - Char Data Type - YouTube
-
C Char Data Type - C Programming
-
How To Play With Strings In C - Coding Game
-
C Keywords: Char
-
Character Constant