Introduction
In C language, strings are stored in an array
of char type along with the null terminating character "\0" at the end. In other
words to create a string in C you create an array of chars and set each element
in the array to a char value that makes up the string. When sizing the string
array you need to add plus one to the actual size of the string to make space
for the null terminating character, "\0". In this tutorial you will learn about
Initializing Strings, Reading Strings from the terminal, Writing strings to
screen, Arithmetic operations on characters, String operations (string.h),
Strlen() function, strcat() function, strcmp function, strcmpi() function,
strcpy() function, strlwr () function, strrev() function and strupr() function.
In C string constants are surrounded by double quotes ("). A string is an array
of characters. Strings must have a 0 or null character after the last character
to show where the string ends. The null character is not included in the string.
There are 2 ways of using strings. The first is with a character array and the
second is with a string pointer.
Different Format of Show the String
- You must set the value of each individual
element of the array to the character you want and you must make the last
character a 0. Remember to use %s when printing the string.
char ca[10];
ca[0] = 'H';
ca[1] = 'e';
ca[2] = 'l';
ca[3] = 'l';
ca[4] = 'o';
ca[5] = 0;
printf("%s",ca);
Some operation of String
-
strcpy
: Used copy of the string.
-
strcat :
Used to add of two string.
-
strcmp
: Used to compare of string.
-
strlen
: Used to get the length of string.
Example : Write a
simple example in String
Code:
#include
<stdio.h>
#include <string.h>
int main()
{ char s1[100],s2[100];
gets(s1);
gets(s2);
if (strcmp(s1,s2)==0)
printf("equal\n");
else if (strcmp(s1,s2)<0)
printf("s1 less than s2\n");
else
printf("s1 greater than s2\n");
return 0;
}
Summary :
This is the simple example that show the compare the two string.