Strings in C
Strings - Basics
• String is an array of characters.
• Each string in C ends with a special character called NULL character ‘\
0’.
‘H’ ‘E’ ‘L’ ‘L’ ‘O’ ‘\0’
Initializing string
char str[ ] = { ‘H’ , ’E’ , ’L’ , ’L’ , ’O’ , ‘\0’ };
Here, the NULL character must be added explicitly,
OR
char str[ ] = “HELLO”;
OR
char str[50]= “HELLO”;
‘H’ ‘E’ ‘L’ ‘L’ ‘O’ ‘\0’
str[0] str[1] str[2] str[3] Str[4] Str[5]
Null Vs. Empty String
Null string
char null_str[20];
Here null_str array is NULL string. It means that null_str has been allocated memory for 20 characters but
hasn’t yet assigned a value.
Empty String
char empty_str[ ] = {‘\0’};
Here array empty_str has one character stored that is ‘\0’.
Printing the length:
printf(“%d” , strlen(empty_str)); // Gives length 0
printf(“%d”, strlen(null_str)); // Gives unpredictable output since its not initialized
Reading String
Two ways of Reading a string
1) Using scanf()
char str[50];
printf(“\n Enter string :”);
scanf(“%s”, str); // no need of writing &
printf(“\n Entered string is : %s “, str);
Output:
Enter string: Hello world
Entered string is : Hello
NOTE : Array name represents base address of the array
str is nothing but &str[0]
Reading string form user
Reading Multiple words using scanf
char str[50];
printf(“\n Enter string: ”);
scanf(“ %[^\n]s”, str); // allows you to read multiple words until user
// hits enter key
printf(“\n Entered string is : %s “, str);
Output:
Enter String : Hello world
Entered string is : Hello world
Reading string form the user
2) Using gets()
char str[50];
printf(“\n Enter string: ”);
gets(str); // will accept multiple words
puts(str);
Buit-In string functions
Defined in <string.h>
strlen(str) - returns length of a string
strcpy(destination, source) – copies source string to destination string
strcmp(str1,str2) – compares str1 with str2. It returns integer
if value > 0 str1 is greater that str2
value =0 strings are equal
value < 0 str1 is less than str2
strcmpi(str1,str2) – ignores case while comparing
strcat(str1,str2) – str2 is concatenated with str2
strrev(str1) – Reverses the given string
Program 1 : Find Length of a string
#include<stdio.h> ‘H’ ‘E’ ‘L’ ‘L’ ‘O’ ‘\0’
int main() str[0] str[1] str[2] str[3] Str[4] Str[5]
{
char str[100];
int i=0;
printf(“\n Enter String”);
scanf(“%s”, str);
while (str[i] != ‘\0’)
{ i++;
}
printf(“\n length of a string is =%d”, i);
}
Length of a string using
function
# include<stdio.h> // Function definition
int strlength(char str[])
# include <string.h>
{
int strlength(char []); // prototype
int i=0;
int main() while (str[i] != '\0')
{ i++;
char str[100]; return i;
int i; }
printf("\n Enter String");
scanf("%s", str);
i = strlength(str);
printf("\n length of a string is =%d", l);
return 0;
}
Program 2: String Copy
strcpy (dest , src);
‘H’ ‘E’ ‘L’ ‘L’ ‘O’ ‘\0’
dest
i=0
src ‘H’ ‘E’ ‘L’ ‘L’ ‘O’ ‘\0’
char dest[50]; // Destination string
char src[50] = “HELLO”; // Source string
int i=0;
while (src[i] != ‘\0’)
{
dest[i] = src[i];
i++;
}
dest[i] = ‘\0’;
String copy using function
int main() void xstrcpy(char s1[ ] , char s2 [ ])
{ {
char src[50] , dest[50]; int i=0;
printf(“\n Enter source string”); while (s2[i] != ‘\0’)
gets(src) ; {
s1[i] = s2[i];
xstrcpy(dest,src);
i++;
printf(“ \n After copy Dest = %s “, dest);
}
}
s1[i] = ‘\0’;
}
Program 3:
Concatenation of int main()
{
two strings char s1[20] = "HELLO";
char s2[20]= "BYE";
int i=0, j=0;
while(s1[i] != '\0') i++;
i 0 1 2 3 4 5 6 7 8 while(s2[j] != '\0')
{
Str1 ‘H’ ‘E’ ‘L’ ‘L’ ‘O’ ‘\0’
s1[i] = s2[j];
i++;
j++;
}
s1[i]='\0';
Str2 ‘B’ ‘Y’ ‘E’ ‘\0’ printf("\nstring 1 is %s" , s1);
printf("\nstring 2 is %s" , s2);
j 0 1 2 3
return 0;
}
String Compare
xstrcmp (s1 , s2)
This function returns an integer value
If value = 0 => s1 =s2
If value > 0 => s1 > s2
If value <0 => s1 < s2
How the strings are actually compared
Strings are compared by comparing ASCII values character by character
Case 1: Equal
Str1 = HELLO
Str2 = HELLO
Case 2 : str1 > str2
Str1 = Natasha
Str2 = Abhishek
Case 3: str1< str2
Str1 : Amit
Str2 : amit
Program 4: String Compare
int main() Case 1: Equal
{ char s1[40] = "Hell"; S1 = HELLO‘\0’
char s2[40] = “Hello"; S2 = HELLO‘\0’
int i=0;
while(s1[i] == s2[i] && s1[i] != '\0') i++; Case 2 : str1 > str2
if (s1[i] < s2[i]) S1 = Natasha ‘\0’
printf("\n s1 < s2"); S2 = Abhishek ‘\0’
else if (s1[i] > s2[i])
Case 3: str1< str2
printf("\n s1 > s2");
S1 : Amit’\0’
else
S2 : amit’\0’
printf("\n s1 = s2");
return 0;
}
Program 5:
String reverse W E L C O M E ‘\0’
0 1 2 3 4 5 6 7
int main()
{ char s[50] = “WELCOME”;
char temp; E E L C O M W ‘\0’
int i = 0;
E M L C O E W ‘\0’
/* find length of string*/
while(s[i] != ‘\0’) i++; E M O C L E W ‘\0’
len=i ;
for( i=0 ; i<len/2 ; i++) E M O C L E W ‘\0’
{
temp = s[i];
i (Len-1)-i
s[ i ] = s[len-1-i]; len = 7
0 6
s[len-1-i] = temp; len-1 = 6
} len /2 = 7/2 = 3 1 5
printf(“\n reverse string is : %s”, s); 2 4
return 0; 3 3
}
String reverse usingvoid
function
xstrrev( char s[ ] )
int main() {
{ char temp;
char s[50] = “WELCOME”; int i = 0, len;
/* find length of string*/
xstrrev(s);
while(s[i] != ‘\0’) i++;
Printf(“\n reverse string is : %s”, s);
len=i ;
return 0; for( i=0 ; i<len/2 ; i++)
} {
temp = s[i];
s[ i ] = s[len-1-i];
s[len-1-i] = temp;
}
}
To check given string is
Palindrome
A string is palindrome is that reads the same backwards as forward,
e.g. madam or malayalam
Logic - palindrome
s M A D A M ‘\0’
i len-1-i • Compare s[ i ] and s[len-1-i ]
0 4 • if you find any mismatch break the loop
1 3
and declare string is not a palindrome
2 2
Program 7 - palindrome
int main()
{ char s[50] = “madam”;
int i , flag = 0 ;
int len = strlen(s);
for( i=0 ; i<len/2 ; i++)
{ if (s[i] ! = s[len-1-i] ) /* mismatch found */
{ flag =1; /* flag =1 means string is not a palindrome*/
break;
}
}
If (flag === 0) printf( “ \n %s is palindrome”, s);
Else
Printf(“\n %s is not a palindrome” ,s);
Return 0;
}
Program 8 - Counting frequency of each
character in a string
/* Find total number of occurrences of each character */
#include <stdio.h> for(i=0; i<len; i++)
#include <string.h> {
#define MAX_SIZE 100 // Maximum string size /* If the current character is lowercase alphabet */
if(str[i]>='a' && str[i]<='z')
int main()
freq[str[i] - 97]++;
{ else if(str[i]>='A' && str[i]<='Z')
char str[MAX_SIZE]; freq[str[i] - 65]++;
int i, len; }
printf("\nFrequency of all characters in the given string: \n");
int freq[26];
for(i=0; i<26; i++)
{
/* Input string from user */ /* If current character exists in given string */
printf("Enter any string: "); if(freq[i] != 0)
printf("'%c' = %d\n", (i + 97), freq[i]);
gets(str); }
len = strlen(str); return 0;
/* Initialize frequency of each character to 0 */ }
for(i=0; i<26; i++)
freq[i] = 0;
Program 10 -Searching a name
in the list
#include<stdio.h>
printf("Enter a string to search: ");
#include<string.h> scanf("%s",s1);
int main()
{ for(i=0; i<n; i++)
char names[20][50], s1[50]; {
int n, i, found=0; if(strcmp(s1, names[i]) == 0)
{
found=1;
printf("Enter how many string (names): "); printf("Found in row-%d\n", i+1);
scanf("%d", &n); }
}
printf("Enter %d strings:\n", n);
if(found==0) printf("Not found");
for(i=0; i<n; i++)
return 0;
{ }
scanf("%s", names[i]);
}
Program 9 - Convert first letter
of Each word into upper case
END OF TOPIC - STRING