C Programming Strings
In C programming, a string is a sequence of characters terminated with a null
character \0. For example:
char c[10] = "c string";
Memory Diagram
How to initialize strings?
You can initialize strings in a number of ways.
char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0'};
Assigning Values to Strings
Arrays and strings are second-class citizens in C; they do not support the
assignment operator once it is declared. For example,
char c[100];
c=- // Error! array type is not assignable.
Read String from the user
You can use the scanf() function to read a string.
Example 1: scanf() to read a string
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Output:
Enter name: Dennis Ritchie
Your name is Dennis.
How to read a line of text?
You can use the fgets() function to read a line of string. And, you can use puts() to
display the string.
Example 2: fgets() and puts()
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
Output:
Enter name: Tom Hanks
Name: Tom Hanks
Passing Strings to Functions
Strings can be passed to a function in a similar way as arrays. Learn more about
passing arrays to a function.
Example 3: Passing string to a Function
#include <stdio.h>
void displayString(char str[]);
int main()
{
char str[50];
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
displayString(str); // Passing string to a function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}
Example 4: Strings and Pointers
#include <stdio.h>
int main(void) {
char name[] = "Harry Potter";
printf("%c", *name); // Output: H
printf("%c", *(name+1)); // Output: a
printf("%c", *(name+7)); // Output: o
char *namePtr;
namePtr = name;
printf("%c", *namePtr); // Output: H
printf("%c", *(namePtr+1)); // Output: a
printf("%c", *(namePtr+7)); // Output: o
}
Loop Through a String
You can also loop through the characters of a string, using a for loop:
Example 5:
#include <stdio.h>
int main() {
char carName[] = "Volvo";
int i;
for (i = 0; i < 5; ++i) {
printf("%c\n", carName[i]);
}
return 0;
}
Commonly Used String Functions
● strlen() - calculates the length of a string
● strcpy() - copies a string to another
● strcmp() - compares two strings
● strcat() - concatenates two strings