Arrays of Strings
Ragged arrays are very common with strings. Consider, for example, the need to store the days of the week in their textual format. We could create a two-dimensional array of seven days by ten characters, but this wastes space.
Operations on Individual Members
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main (void)
{
char str1 [501, str2[50], str3[50]; //Declaring strings
int len1 = 0, len2 = 0, i = 0, i1= 0;
// Calculate and print the length of the string
printf ("Please Enter String 1: ");
scanf("%s", str1);
while (str1 [len 1 ] != ‘\0')
len1 = len1+1;
printf("The length of the string calculated is: %d\n", len1);
printf("Using strlen:\n");
printf("The length of the string: %d\n", strlen(str1) ); // This should match with the computed one
// Compare two strings and print result Equal or Not Equal
printf ("Please enter string 2: ");
scanf ("%s", str2);
len2 = strlen(str2);
if (len1 = len2)
while (str1 [i] = str2[i]) i = i-1-, // If there is a mismatch come out of loop
if (len1!= len2 Ii i < len1)
/* Either strings have unequal lengths or there was a mismatch at some position*/
printf ("Strings are Not Equal");
else
printf (" \nStrings are Equal");
printf (" \nUsing strcmp:");
printf (strcmp(strl,str2) ?"\n Strings are Not Equal": "\n Strings are Equal"); /* strcmp compares two strings and returns zero if they are the same */
// Copy string 1 to string 3
i = 0;
while (strl [i] != '\0') //Copy strl to str3, one character at a time
{
str3[i] = str1 [i];
i++,
}
str3 [i] = ‘\0’;
printf (" \nstr1 copied to str3:\n");
printf ("str1 = %s and str3 = %s \n", str1, str3);
printf("concatenating strings");
i = strlen(str1);
while (str2[il] != '\0') // concatenate second string to firs one, one character at a time
{
str1 [i] = str2[i]I;
i1 = i1++;
i = i++,
}
str1[i]= 0;
printf(" \n%s and the length is %d\n", str1, i);
printf("Using strcat:\n%s", strcat(str3, stx2 )); /* strcat cocatenates the second string i.e. str2 to the end of the first string i.e. str3 */
printf(" and the length is %d\n", strlen(str3));
return 0;
}
Output:
Please Enter String 1: globarena
The length of the string calculated is: 9
Using strlen:
The length of the string: 9
Please enter string 2: Hyderabad
Strings are Not Equal Using strcmp:
Strings are Not Equal
strl copied to str3:
strl = globarena and str3 = globarena
concatenating strings
globarenaHyderabad and the length is 18
Using strcat:
globarenaHyderabad and the length is 18