36. Strings


When dealing with strings in C, you should always think of the underlying array of characters.
Also: always think in terms of the activation records! You must explicitly allocate all the space for every string you use.


String Example


void main()
{
char s[] = "Hi!"; // initialization with string constant
char s2[] = { 'H' , 'i' , '!' , '\0' };
// initialization with char constant
int i;
for( i = 0; s[i] != 0; i++ )
printf( "%c_%c_", s[i], s2[i] );




}


Output: H_H_i_i_!_!_



String input


Alternative way of taking string input


char str[80];
scanf(“%s”, str);
scanf(“%s”, &str[0]);
gets(str);
for(i=0; i<10;i++)
scanf(“%c”, &str[i]);

String handling functions These are from string.h library. (You have to #include to use these functions).
int strlen( char *s ); Returns the length of the string s.
strlen(“hello”) will return the value 5
char *strcat( char *s1, char *s2 ); Takes two strings as arguments, concatenates them, and puts the result in s1.
The programmer must ensure that s1 points to enough space to hold the result. The string s1 is returned.
strcat(“hello”, “_world”) will return string “hello_world”



char *strcpy( char *s1, char *s2 );
The string s2 is copied into s1.
Whatever exists in s1 is overwritten. It is assumed that s1 has enough space to hold the result. The value of s1 is returned.
strcpy(s1, s2) will return s1 with the new value copied from s2


(Remember, using = to assign one string to another only copies pointers, it doesn’t actually give a new copy of the string. And it won’t work at all if the left hand side is a string array.)


int strcmp( char *s1, char *s2 ); Integer is returned that is less than, equal to, or greater than zero, depending on whether s1 is lexicographically less than, equal to, or greater than s2 (respectively).


strcmp(“he”, “hi”) will return less than 0
strcmp(“12”, “12”) will return 0
strcmp(“they”, “the”) will return greater than 0

Post by j.siam,
Ref-: Md Munirul Haque

No comments:

Post a Comment

free counters