String:
A String is a single character treated as a single unit. A String may include letters, digits and various special characters such as +, -, *, / and $. Strings literals or string constants in c are written in double quotation marks as follows:
“1000 Main Street” (a street address)
“(080)329-7082” (a telephone number)
In C, language strings are stored in array of char type along with null terminating character ” at the end.
1. Declaration and Initialization:
Strings can be declared and initialized using an array of characters:
#include <stdio.h>
int main() {
// Declaration and initialization of a string
char greeting[] = “Hello, World!”;// Alternatively, you can declare a string without initialization and later assign a value
// char greeting[20];
// strcpy(greeting, “Hello, World!”);// Printing the string
printf(“%sn”, greeting);return 0;
}
2. Processing Strings:
a. Inputting a String:
#include <stdio.h>
int main() {
char name[50];// Inputting a string
printf(“Enter your name: “);
scanf(“%s”, name);// Printing the inputted string
printf(“Hello, %s!n”, name);return 0;
}
b. String Functions:
C provides standard library functions for working with strings. Here are a few examples:
#include <stdio.h>
#include <string.h>int main() {
char str1[20] = “Hello”;
char str2[] = “, World!”;// Concatenating strings using strcat
strcat(str1, str2);
printf(“Concatenated string: %sn”, str1);// Copying strings using strcpy
char copy[20];
strcpy(copy, str1);
printf(“Copied string: %sn”, copy);// Finding the length of a string using strlen
printf(“Length of str1: %lun”, strlen(str1));// Comparing strings using strcmp
char cmpStr[] = “Hello, World!”;
if (strcmp(str1, cmpStr) == 0) {
printf(“str1 is equal to cmpStr.n”);
} else {
printf(“str1 is not equal to cmpStr.n”);
}return 0;
}