Strings In C
String in C language is an array of characters that is terminated by \0 (null character). There are two ways to declare string in c language.
Difference between char array and string literal
The only difference is that string literal cannot be changed whereas string declared by char array can be changed.String Example in C
Let's see a simple example to declare and print string. The '%s' is used to print string in c language.#include <stdio.h> void main () { char ch[13] = {'c','a','t','c','h','m','e','c','o','d','e','r','\0'}; char ch2[13] = "catchmecoder"; printf("Char Array element is: %s\n", ch); printf("String Literal element is: %s\n", ch2); } Output: Char Array element is: catchmecoder String Literal element is: catchmecoder
C gets() and puts() functions
The gets() function reads string from user and puts() function prints the string. Both functions are defined in
There are many important string functions defined in "string.h" library.
The strlen() function returns the length of the given string. It doesn't count null character '\0'.
The strcpy(destination, source) function copies the source string in destination.
#include <stdio.h>
void main() {
char name[60];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
}
Output:
Enter your name: pramesh gupta
Your name is: pramesh gupta
String Functions
No. Function Description 1 strlen(string_name) returns the length of string name. 2 strcpy(destination, source) copies the contents of source string to destination string. 3 strcat(first_string, second_string) concats or joins first string with second string. The result of the string is stored in first string. 4 strcmp(first_string, second_string) compares the first string with second string. If both strings are same, it returns 0. 5 strrev(string) returns reverse string. 6 strlwr(string) returns string characters in lowercase. 7 strupr(string) returns string characters in uppercase. C String Length: strlen() function
#include <stdio.h>
void main()
{
char ch[30] = {'c', 'a', 't', 'c', 'h', 'm', 'e ', 'c', 'o', 'd', 'e', 'r', '\0'};
printf("Length of string is: %d",strlen(ch));
}
Output:
Length of string is: 12
C Copy String: strcpy()
#include <stdio.h>
void main()
{
char ch[30] = {'c', 'a', 't', 'c', 'h', 'm', 'e', 'c', 'o', 'd', 'e', 'r', '\0'};
char ch2[30];
strcpy(ch2,ch);
printf("element of second string is: %s",ch2);
}
Output:
element of second string is: catchmecoder