Strings And String Functions

StringA 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 ‘’ 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.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(‘’) character.
Always keep in mind that the ‘’ 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 ‘’ 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;
}OutputI Love CodingThis 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(”%sn”,str1);
Printf(”%sn”,str2);
return 0;
}OutputI Like
C Programmingscaning 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 memorylocation.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 ‘’ 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(‘’) 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() functionIt is one of the most useful functions used from this library, whenever we need the length of the string say “str1″we write it asint 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(‘’) character.strcpy( dest, source)This function copies the string “source” to string “dest”.Declarationstrcpy( str2, str1 );Return valueThis returns a pointer to the destination string dest.ExampleBelow 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) = %sn”, str1 ) ;
printf ( “dest string(i.e str2) = %sn”, str2) ;
strcpy ( str2, str1 ) ;
printf ( “target( i.e str2) string after strcpy( ) = %sn”, str2 ) ;
return 0;
}Outputsource string(i.e str1) = I love programming
dest string(i.e str2) =
target( i.e str2) string after strcpy( ) =I love programmingit is also easy to copy one string to another via a for loop, asint 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]=’’; // don’t ever forget to terminate the string with ‘’.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() functionstrcmp( 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 equaln”,str1,str2);
}
else
printf(“string %s and string %s are not equaln”,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 str2Normal approach for comparing two strings isvoid 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 equaln”,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 equaln”,str1,str);
break;
}
}
if(i==l1){ //if the for loop has ran for the whole l1 lenth.
printf(“string %s and string %s are equaln”,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 ‘’ character is not compared.Declarationstrstr( 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 valueThis 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.ExampleBelow 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 foundn” ); //i.e str2 is a substring of str1.
printf (“First occurrence of string “test”” in “”%s”” is””

News Reporter

Leave a Reply

Your email address will not be published. Required fields are marked *