Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’
Syntax:
char str_name[size];
Initialization of String:
1. char str[] = "Hello World";
2. char str[20] = "Hello_World";
3. char str[] = {'H','e','l','l','o',' ','W','o','r','l','d','\0'};
4. char str[13] ={'H','e','l','l','o',' ','W','o','r','l','d','\0'};
2. char str[20] = "Hello_World";
3. char str[] = {'H','e','l','l','o',' ','W','o','r','l','d','\0'};
4. char str[13] ={'H','e','l','l','o',' ','W','o','r','l','d','\0'};
We can initialize string four different way.Most commonly uses is first one.
To Print & Store String:
The C language does not provide an inbuilt data type for strings but it has an access specifier “%s” which can be used to directly print and read strings.
\\syntax for printing string
\\syntax for printing string
\\syntax for storing string
Functions in Strings:
String.h header file supports all the string functions in C language. All the string functions are given below.
1.strcat: The strcat() function will append a copy of the source string1 to the end of destination string2.
Example:
#include <stdio.h>
#include <string.h>//String Header File
int main ()
{
char str1[12] = "Hello";
char str2[12] = "World";
strcat( str1, str2);//content of str2 is connected after with content of str1.
printf("%s",str1);
}
Output:
2.strcpy:The strcpy() function will copy the content on one string1 into the string2.
Example:
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[12] = "Hello";
char str2[12] = "World";
strcpy(str2, str1); //Copied content of Str1 into str2
puts(str2);
}
3.strlen:The strlen() function used to calculate the length of string.
Example:
#include <stdio.h>
#include <string.h>
int main ()
{
int len ;
char str1[12] = "Hello";
len = strlen(str1);// This Function returns int value.
printf("strlen(str1) : %d\n", len );
}
Output:
4.strcmp:The strcmp() function is used to compare the two strings and return 0 if both the strings are equal.
Example:
#include<stdio.h>
#include <string.h>
int main()
{
char str1[10]="GURU";
char str2[10]="GURU";
if(strcmp(str1,str2)==0)// return 0 if both the strings are equal.
printf("Strings :equal");
else
printf("Strings: not equal");
}
Output:
1.WAP to find the String is palindrome or not.
#include <stdio.h>
#include <string.h>
void main()
{
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string:");
scanf("%s", string1);
length = strlen(string1);
for(i=0;i < length ;i++)
{
if(string1[i] != string1[length-i-1])
{
flag = 1;
break;
}
}
if (flag)
{
printf("%s is not a palindrome", string1);
}
else
{
printf("%s is a palindrome", string1);
}
}
Output:
0 Comments