Strings in C
In real programs, we don’t work only with numbers. We work with names, messages, sentences, and text.
In C, text data is handled using strings. Understanding strings is very important because they are used almost everywhere.
What Is a String?
In C, a string is a collection of characters stored in a character array.
Every string in C ends with a special character:
\0 (null character)
This null character tells the compiler where the string ends.
String as a Character Array
Since strings are stored in arrays, everything you learned about arrays applies to strings as well.
Example:
char name[5] = {'J','o','h','n','\0'};
This creates a string "John".
String Declaration (Shortcut Method)
C provides an easier way to declare strings.
char name[] = "John";
Here, the compiler automatically adds \0
at the end.
Printing a String
Strings are printed using the %s
format specifier.
#include <stdio.h>
int main() {
char name[] = "Dataplexa";
printf("Welcome to %s", name);
return 0;
}
Reading a String from User
Strings can be read using scanf(),
but it stops reading at whitespace.
char name[20];
scanf("%s", name);
This reads only one word.
Reading a Full Line (Using fgets)
To read a full sentence including spaces,
we use fgets().
#include <stdio.h>
int main() {
char message[50];
fgets(message, 50, stdin);
printf("%s", message);
return 0;
}
This is the recommended method for reading strings safely.
String Library Functions
C provides built-in functions for string operations
in the <string.h> header.
strlen()– length of stringstrcpy()– copy stringstrcat()– concatenate stringsstrcmp()– compare strings
Example: Finding Length of String
#include <stdio.h>
#include <string.h>
int main() {
char word[] = "Programming";
printf("Length = %d", strlen(word));
return 0;
}
Real-World Thinking
Strings are used to store:
- User names
- Email addresses
- Passwords
- Messages
Almost every application relies heavily on strings.
Common Mistakes
- Forgetting the null character
- Using wrong array size
- Using scanf for full sentences
These mistakes can cause unexpected behavior.
Mini Practice
- Store your name in a string and print it
- Find the length of a user-entered string
- Read a sentence and display it
Quick Quiz
Q1. What is a string in C?
A string is a collection of characters stored in a character array ending with \0.
Q2. Which character marks the end of a string?
The null character (\0).
Q3. Which format specifier is used for strings?
%s
Q4. Which function safely reads a full line?
fgets()
Q5. Which header file contains string functions?
string.h