String in C
String in C
#include <stdio.h>
int main () {
char string[10] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Message is: %s\n", string);
return 0;
}
String Input and Output function:
Input function scanf() can be used with %s format specifier to read a string
input from the
terminal. But there is one problem with scanf() function, it terminates its input
on the first white space it encounters. Therefore if you try to read an input string
"Hello World"
using scanf() function, it will only read Hello and terminate after encountering
white spaces.
How to read a line of text?
You can use the gets() function to read a line of string. And, you can
use puts() to display the string.
Example : gets() and puts()
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
Write a program to illustrate various string inbuilt functions (strcmp, strlen,
strcpy, strcat).
Program:
#include <stdio.h>
#include <string.h>
int main()
{
char name[10];
char name2[10] = "DEF";
strcpy(name, "ABC");
printf("\n Name is: %s",name);
strcat(name, name2);
printf( "\n strcat( name, name2): %s" , name );
int len;
len = strlen(name);
printf( "\n strlen(name) : %d",len);
if(strcmp(name,name2)==0)
printf(" \n Strings are equal");
else
printf(" \n Strings are not same");
return 0;
}
#include <stdio.h>
#include <math.h>
#include <string.h>
int main()
{
unsigned short count = 0, vowels = 0;
char str[100], c;
printf("Enter a string in which you want to find number of vowels: ");
scanf("%[^\n]", str);
while(str[count] != '\0')
{
c = str[count];
if(c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I'
|| c == 'o' || c == 'O' || c == 'u' || c == 'U') {
vowels++;
printf("%c", c);
}
count++;
}
printf("\n");
printf("NUMBER OF VOWELS In Given string Are: %hu \n", vowels);
}
return 0;
}
return 0;
}
Compare two strings
#include <stdio.h>
int main() {
char str1[100], str2[100];
int i = 0, isEqual = 1; // isEqual is used to track if strings are equal
// Get two strings from the user
printf("Enter the first string: ");
fgets(str1,sizeof(str1),stdin);
printf("Enter the second string: ");
fgets(str2,sizeof(str2),stdin);
// Compare the strings character by character
while (str1[i] != '\0' || str2[i] != '\0') {
if (str1[i] != str2[i]) {
isEqual = 0; // If characters are different, mark as not equal
break;
}
i++;
}
// Check if strings are equal
if (isEqual == 1) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}
return 0;
}