47
Strings And String Functions
String
Basic
String.h

String

A string in C is actually a character array. As an individual character variable can store only one character, we need an array of characters to store strings. Thus, in C string is stored in an array of characters. Each character in a string occupies one location in an array. The null character ‘\0’ is put after the last character. This is done so that program can tell when the end of the string has been reached. For example, the string “Hello” is stored as follows. enter image description here

Since the string contains 5 characters. it requires a character array of size 6 to store it. the last character in a string is always a NULL('\0') character. Always keep in mind that the '\0' is not included in the length if the string, so here the length of the string is 5 only. Notice above that the indexes of the string starts from 0 not one so don't confuse yourself with index and length of string.

Thus, in C, a string is a one-dimensional array of characters terminated a null character. The terminating null character is important. In fact, a string not terminated by ‘\0’ is not really a string, but merely a collection of characters. A string may contain any character, including special control characters, such as \n, \t, \ etc...
There is an important distinction between a string and a single character in C. The convention is that single characters are enclosed by single quotes e.g. '' and have the type char. Strings, on the hand, are enclosed by double quotes e.g. "name" and have the type "pointer to char" (char ) or array of char.

Strings can be declared in two main ways; one of these is as an array of characters, the other is as a pointer to some pre-assigned array.
Perhaps the simplest way of seeing how C stores arrays is to give an extreme example which would probably never be used in practice.

#include<stdio.h>
int main (){ 
      char str[20];
       str[0]='I';
       str1=' ';
       str2='L';
       str3='o';
       str[4]='v';
       str[5]=' ';
       str[6]='C';
       str[7]='o';
       str[8]='d';
       str[9]='i';
       str[10]='n';
       str[11]='g'
       printf ("%s", str);
       return 0;
      }

Output
I Love Coding

This method of handling strings is perfectly acceptable, if you got time to waste, but it is so laborious that C provides a special initialization service for strings, which bypasses the need to assign every single character with a new assignment.
The other way is use a pointer to some pre-assigned array. Assignment of str2 is of the pointer type.

#include<stdio.h>
int main ()
      {
      char str1[]=”I Like”;
      char *str2=”C Programming”; 
      Printf(”%s\n”,str1);
      Printf(”%s\n”,str2);
      return 0; 
}

Output

I Like
C Programming

scaning a string:

char str[100];
scanf("%s",str);

Memory:

As we know that each character occupies 1 byte, so a string of lenght L will have a size of L bytes. -Always keep in mind that each of the characters in the string is stores in consecutive memory
location.

Because C has no built-in facilities for manipulating entire arrays (copying them, comparing them, etc.), it also has very few built-in facilities for manipulating strings.
In fact, C's only truly built-in string-handling is that it allows us to use string constants (also called string literals) in our code. Whenever we write a string, enclosed in double quotes, C automatically creates an array of characters for us, containing that string, terminated by the '\0' character.
For example, we can declare and define an array of characters, and initialize it with a string constant:

 char string[] = "Hello, world!";

In this case, we can leave out the dimension of the array, since the compiler can compute it for us based on the size of the initializer (14 including the spaces and the NULL('\0') character). This is the only case where the compiler sizes a string array for us, however; in other cases, it will be necessary that we ourselves decide how big the arrays and other data structures we use to hold strings are.
*-It is always a good idea to initialize a string with some lareg size as compared to largest size of string given in the problem.*

To do anything else with strings, we must typically call functions. The C library contains a few basic string manipulation functions, and to learn more about strings, we'll be looking at how these functions might be implemented.


String functions

#include<string.h>
include this library to your program to use some of the inbuilt string manipulation functions present in the library.

there are about 20-22 inbuilt string manipulating functions present in this library.
The most common functions used from the library are:
1. strlen("name of string")
2. strcpy( dest, source)
3. strcmp( string1, string2 )
4. strstr( str1, str2 )

strlen( string )

Declaration and usage of strlen() function

It is one of the most useful functions used from this library, whenever we need the length of the string say "str1"
we write it as

int len;
len = strlen(str1);
len will be the length of the string "str1".(it will include all the spaces and characters in the string except the NULL('\0') character.

strcpy( dest, source)

This function copies the string "source" to string "dest".
Declaration

strcpy( str2, str1 );

Return value
This returns a pointer to the destination string dest.

Example
Below code shows the usage of strcpy() function.

#include<stdio.h>
#include<string.h> int main( ) { char str1[ ] = "I love programming" ; char str2[20]= "" ; printf ( "source string(i.e str1) = %s\n", str1 ) ; printf ( "dest string(i.e str2) = %s\n", str2) ; strcpy ( str2, str1 ) ; printf ( "target( i.e str2) string after strcpy( ) = %s\n", str2 ) ; return 0; }
Output

source string(i.e str1) = I love programming
dest string(i.e str2) = 
target( i.e str2) string after strcpy( ) =I love programming
it is also easy to copy one string to another via a for loop, as
int i,len;
len=strlen(str1);
for( i=0 ; i < len ; i++ ){
       str2[i]=str1[i];
}
//last index in the string was len-1
//now outside for loop value of i=len.
str2[i]='\0';    // don't ever forget to terminate the string with '\0'.

either way is good to copy but using strcpy is a good habit to have.

strcmp( str1, str2 )

This function is used to compare two strings "str1" and "str2". this function returns zero("0") if the two compared strings are equal, else some none zero integer.
Declaration and usage of strcmp() function

strcmp( str1 , str2 );    //declaration
//using this function to check given two strings are equal or not.
if( strcmp( str1, str2 )==0){
         printf("string %s and string %s are equal\n",str1,str2);
}
else
       printf("string %s and string %s are not equal\n",str1,str2);

Return value
- if Return value if < 0 then it indicates str1 is less than str2
- if Return value if > 0 then it indicates str2 is less than str1
- if Return value if = 0 then it indicates str1 is equal to str2
Normal approach for comparing two strings is
void compare( char str1[], char str2[]){
int l1,l2,i;
l1=strlen(str1);
l2=strlen(str2);
if(l1!=l2){
     printf("string %s and string %s are not equal\n",str1,str);
}
else{
        for( i = 0; i < l1 ; i++){   // l1 or l2 anyone as both are equal.
                if(str1[i]!=str2[i]){
                     printf("string %s and string %s are not equal\n",str1,str);
                     break;
                }
       }
       if(i==l1){      //if the for loop has ran for the whole l1 lenth.
               printf("string %s and string %s are equal\n",str1,str);
       }
    }
}
you can yourself see that the first comparing approach is always better and time saving too.

strstr(str1, str2)

This library function finds the first occurrence of the substring str2 in the string str1. The terminating '\0' character is not compared.
Declaration

 strstr( str1, str2);
 - str1: the main string to be scanned.
 - str2: the small string to be searched in str1. 
// let say str2="speed"; //function can also be written as strstr(str1, "speed" );
This function is very useful in checking whether str2 is a substring of str1 or not.
Return value
This function returns a pointer to the first occurrence in str1 of any of the entire sequence of characters specified in str2, or a NULL pointer if the sequence is not present in str1.


Example
Below code shows the usage of strstr() function.

#include<stdio.h>
#include<string.h> int main () { char str1[55] ="This is a test string for testing"; char str2[20]="test";
char *p; p = strstr (str1, str2); if(p) { printf("string found\n" ); //i.e str2 is a substring of str1. printf ("First occurrence of string \"test\" in \"%s\" is"\ " \"%s\"",str1, p); } else printf("string not found\n" ); // str2 is not a substring of str1. return 0; }
Output

string found
First occurrence of string “test” in “This is a test string for testing” is “test string for testing”

Above explained two functions strcpy() and strcmp() can also be extended to n characters in the following way:

strncpy(dest, source,n)
Copies up to n characters from the string pointed to, by source to dest.
strncmp(str1, str2, n)
Compares at most the first n bytes of str1 and str2.


for the reference to other functions in the <string.h> library go to string.h

Author

Notifications

?