Sunday, 7 November 2010

38.Array Of Strings

Strings: they’re just arrays!
Strings are one-dimensional arrays of chars.
By convention, a string in C is terminated by the null character, ’\0’, or 0. (We have ’\0’ == 0.)
String constants (such as those passed to the function printf) are enclosed in double quotes.
When allocating char arrays that will hold strings, make sure you allocate enough space!

Array Of Strings

Declaration:
char arr[8][81];
// allocates 8 string space each with 80 character length

Input
scanf(“%s”, arr[2]);
scanf(“%s”, &arr[2][0]);
gets(arr[2]);
gets(&arr[2][0]);


void main()
{
char arr[8][81];
scanf( "%s", arr[1] );
printf( "Length of your string: " );
printf( "%d\n", strlen(arr[1] ));

printf( "You typed the string: %s\n", arr[1] );
printf( "The first character you typed was: " );
printf( "%c\n", arr[1][0] );
}


Two-dimensional array of chars acts as array of strings (of size 8): arr[0], ..., arr[7]
scanf( "%s", ... ); used to read strings.
To refer to a specific character of one of the strings arr[i], tack on another index:
arr[1][0] for instance refers to the first (zero-indexed) character of the string arr[1].

String matching

void main()
{
char s1[20], s2 [20];
strcpy( s2, "Hello" );
strcpy(s1, s2);

for(i=0; i if( s1[i] != s2[i] ) {
printf(“Not equal”);
break;
printf(“String s1 and s2 is equal at character index %d”, i);
}
}

Post by J.siam
Ref Herbert Schildt

No comments:

Post a Comment