You are on page 1of 13

Strings

Introduction
o Strings in C are group of characters, digits, and symbols enclosed in quotation marks or simply we can say the string is declared as a character array. o The end of the string is marked with a special character, the \0 (Null character), which has the decimal value 0. o There is a difference between a character stored in memory and a single character string stored in a memory. o The character requires only one byte whereas the single character string requires two bytes (one byte for the character and other byte for the delimiter).
y

Strings are stored in memory as ASCII codes of characters that make up the string appended with \0 (ASCII value of null). Normally each character is stored in one byte; successive characters are stored in successive bytes. For example, the sentence "my age is 2 (two)" will be stored as
m 77 y 121 32 a 97 g 103 e 10 32 i 105 s 115 32 2 50 32 ( 40 t 116 w 119 o 41 ) 0 \0 0

Character ASCII code

The last character is the null character having ASCII value zero.

y y

Declaration of strings o A string in C is simply a sequence of characters. To declare a string, specify the data type as char and place the number of characters in the array in square brackets after the string name. The syntax is shown as below: Syntax: o char string-name[size]; Where the size determines the number of characters in the string name. Example: char month[10]; char address[100]; Rule: The size of the array should be one byte more than the actual space occupied by the string since the complier appends a null character at the end of the string.

Initializing Strings A string can be initialized similar to the initialization of 1-D character array as shown below char month1[ ]={j,a,n,u,a,r,y}; Then the string month1 is initializing to January. The string can be initialized in another way as shown below char month1[]=January; The characters of the string are enclosed within a part of double quotes. The compiler takes care of storing the ASCII codes of characters of the string in the memory and also stores the null terminator in the end.

y y y y

Example to take string as input and display the string #include < stdio.h > main() { char month[15]; printf (Enter the string); gets (month); printf (The string entered is %s, month); } In this example string is stored in the character variable month the string is displayed in the printf statement. Format specifier for string is %s month is one dimension array. Each character occupies a byte. A null character (\0) that has the ASCII value 0 terminates the string. The characters of strings are stored in the contiguous (adjacent) memory locations. The figure shows the storage of string January in the memory
J 1001 A 1002 N 1003 U 1004 A 1005 R 1006 Y 1007 \0 1008

y y

A string variable is any valid C variable name and is always declared as an array.

Reading Strings from the terminal: The function scanf with %s format specification is needed to read the character string from the terminal. Example: char address[15]; scanf(%s,address); scanf statement has a drawback that it just terminates the statement as soon as it finds a blank space, suppose if we type the string new york then only the string new will be read and since there is a blank space after word new, it will terminate the string. To read an entire line of text from the terminal including spaces we have to use gets() function. The function getchar() can be used to read a single character at a time and store it in the array. We cannot manipulate strings since C does not provide any operators for string. For instance we cannot assign one string to another directly. Example: The following statements are not valid. string=xyz; //can be done while initializing string variable string1=string2; //cant be done at any time We can assign strings to string variables directly at the time of initialization only. Writing strings to screen: The printf statement along with format specifier %s can be used to print strings on to the screen. For example, printf(%s,name); can be used to display the entire contents of the array name. Arithmetic operations on characters: We can also manipulate the characters as we manipulate numbers in c language. Whenever the system encounters the character data it is automatically converted into an integer value by the system. We can represent a character as an integer by using the following method. X=a;

printf(%d\n,x); will display 97 (ASCII value of a) on the screen. Arithmetic operations can also be performed on characters. Example: The following statement is valid. x=z-1; The value of x will be 121 as the ASCII value of z is 122. It is also possible to use character constants in relational expressions Example: ch>a && ch < = z will check whether the character stored in variable ch is a lower case letter. A character digit can also be converted into its equivalent integer value. Example: char character=8; int a=character-1; Here a will calculated as ASCII value of 8 - ASCII value 1=56-49=7.

String Constants Example of String constant String operations (string.h) C language recognizes that string is a different class of array by letting us input and output the array as a unit and is terminated by null character. C library supports a large number of string handling functions to do the string manipulations such as: Length (number of characters in the string). Concatenation (adding two are more strings) Comparing two strings. Substring (Extract substring from a given string) Copy(copies one string over another)

To do all the operations described here it is essential to include string.h library header file in the program. strlen() function: This function counts and returns the number of characters in a string. The length does not include a null character. Syntax:
strlen(string);

Return value: An integer to receive the value of length of the string. Example: length=strlen(Hollywood); The function will assign number of characters 9 in the string to an integer variable length. Example to write a c program to find the length of the string using strlen() function #include < stdio.h > include < string.h > void main() { char name[100]; int length; printf(Enter the string); gets(name); length=strlen(name); printf(\nNumber of characters in the string is=%d,length); }

The strcat function is used to join one string to another. It takes two strings as arguments; the characters of the second string will be appended to the first string. The syntax is as follows: strcat(str1, str2);

where str1 and str2 are two string arguments, string str2 is appended to string str1.

Write a program to read two strings and append the second string to the first string. /* Program for string concatenation*/ #include <stdio.h> #include <string.h> main() { char first[80], second[80]; printf(Enter a string:); gets(first); printf(Enter another string: ); gets(second); strcat(first, second); printf(\nThe two strings joined together: %s\n, first); } strncat function The strncat function is the same as strcat, except that it appends upto specified length. The syntax is as follows: strncat(str1, str2,10); where 10 character of the str2 string is added into str1 string. 1. Strcpy Function In C, you cannot simply assign one character array to another. You have to copy element by element. The string library <string.h> contains a function called strcpy for this purpose. The strcpy function is used to copy one string to another. The syntax is as follows: strcpy(str1, str2); where str1, str2 are two strings. The content of string str2 is copied on to string str1. Write a program to read a string from the keyboard and copy the string onto the second string and display the strings on to the monitor by using strcpy( ) function. /* Program to illustrate strcpy function*/ #include <stdio.h> #include <string.h> main() { char first[80], second[80]; printf(Enter a string: ); gets(first); strcpy(second, first); printf(\n First string is : %s, and second string is: %s\n, first, second); } OUTPUT Enter a string: ssccs First string is: ssccs, and second string is: ssccs

strncpy function The strncpy function same as strcpy. It copies characters of one string to another string up to the specified length. The syntax is as follows: strncpy(str1, str2, 10); where str1 and str2 are two strings. The 10 characters of string str2 are copied onto string str1. 2. Strcmp Function The strcmp function in the string library function which compares two strings, character by character and stops comparison when there is a difference in the ASCII value or the end of any one string and returns ASCII difference of the characters that is integer. If the return value zero means the two strings are equal, a negative value means that first is less than second, and a positive value means first is greater than second. The syntax is as follows: n = strcmp(str1, str2); where str1 and str2 are two strings to be compared and n is returned value of differed characters. Write a program to compare two strings using string compare function. /* The following program uses the strcmp function to compare two strings. */ #include <stdio.h> #include <string.h> main() { char first[80], second[80]; int value; printf(Enter a string: ); gets(first); printf(Enter another string: ); gets(second); value = strcmp(first,second); if(value == 0) printf(The two strings are equal); else if(value < 0) printf(The first string is smaller ); else if(value > 0) printf(the first string is bigger); } OUTPUT Enter a string: MOND Enter another string: MOHANT The first string is smaller

stricmp function The stricmp function is same as strcmp, except it compares two strings ignoring the case (lower and upper case). The syntax is as follows: n = stricmp(str1, str2); strncmp function The strncmp function is same as strcmp, except it compares two strings up to a specified length. The syntax is as follows: n = strncmp(str1, str2, 10); where 10 characters of str1 and str2 are compared and n is returned value of differed characters. 3. Strlwr Function The strlwr function converts upper case characters of string to lower case characters. The syntax is as follows: strlwr(str1); where str1 is string to be converted into lower case characters. Write a program to convert the string into lower case characters using in-built function. /* Program that converts input string to lower case characters */ #include <stdio.h> #include <string.h> main() { char first[80]; printf("Enter a string: "); gets(first); printf("Lower case of the string is %s, strlwr(first)); } OUTPUT Enter a string:SSCCS Lower case of the string is ssccs 4. strupr function The strupr function converts lower case characters of the string to upper case characters. The syntax is as follows: strupr(str1); where str1 is string to be converted into upper case characters. Write a program to convert the string into Upperr case characters using in-built function.

/* Program that converts input string to Uppercase characters */ #include <stdio.h> #include <string.h> main() { char first[80]; printf("Enter a string: "); gets(first); printf("Upper case of the string is %s, strupr(first)); } OUTPUT Enter a string:SSCCS Uppercase of the string is ssccs

5. Strrev Function The strrev funtion reverses the given string. The syntax is as follows: strrev(str); where string str will be reversed. Write a program to reverse a given string. /* Program to reverse a given string */ #include <stdio.h> #include <string.h> main() { char first[80]; printf(Enter a string:); gets(first); printf(\n Reverse of the given string is : %s , strrev(first)); } OUTPUT Enter a string: ADANY Reverse of the given string is: YNADA 6. Strspn Function The strspn function returns the position of the string, where first string mismatches with second string. The syntax is as follows: n = strspn (first, second); where first and second are two strings to be compared, n is the number of character from which first string does not match with second string. Write a program, which returns the position of the string from where first string does not match with second string.

/*Program which returns the position of the string from where first string does not match with second string*/ #include <stdio.h> #include <string.h> main() { char first[80], second[80]; printf("Enter first string: ); gets(first); printf(\n Enter second string: ); gets(second); printf(\n After %d characters there is no match,strspn(first, second)); } OUTPUT Enter first string: ALEXANDER Enter second string: ALEXSMITH After 4 characters there is no match 7. strset function The strset funtion replaces the string with the given character. It takes two arguments the string and the character. The syntax is as follows: strset (first, ch); where string first will be replaced by character ch. Write a program to read two strings and Replace the second string to the first string. /* Program for string Replace String*/ #include <stdio.h> #include <string.h> main() { char first[80], second[80]; printf(Enter a string:); gets(first); printf(Enter another string: ); gets(second); strset(first, second); printf(\nThe two strings joined together: %s\n, first); }

strtok() function: This function is used to find the next token in a string. Syntax:

strtok(string, delimiter);

Where string is the whole string in which search is to be done and delimiter is any character string that is to be searched in the string Return value: Returns a pointer to the next token found in string. Returns NULL when no more tokens are found Example to use strtok #include <string.h> #include <stdio.h> char string[] = "A string\tof ,,tokens\nand some more tokens"; char seps[] = " ,\t\n"; char *token; void main( void ) { printf( "%s\n\nTokens:\n", string ); /* Establish string and get the first token: */ token = strtok( string, seps ); while( token != NULL ) { /* While there are tokens in "string" */ printf( " %s\n", token ); /* Get next token: */ token = strtok( NULL, seps ); } } Output A string of ,,tokens and some more tokens

Example program to use string functions #include < stdio.h > #include < string.h > void main() { char s1[20],s2[20],s3[20]; int x,l1,l2,l3; printf(Enter the strings); scanf(%s%s,s1,s2); x=strcmp(s1,s2); if(x!=0) { printf(\nStrings are not equal\n); strcat(s1,s2); } else printf(\nStrings are equal); strcpy(s3,s1); l1=strlen(s1); l2=strlen(s2); l3=strlen(s3); printf(\ns1=%s\t length=%d characters\n,s1,l1); printf(\ns2=%s\t length=%d characters\n,s2,l2); printf(\ns3=%s\t length=%d characters\n,s3,l3); }

Two dimensional array of characters: 2-D array of characters can be written as shown in the following example main() { char names[4][10]={krishna,rama,malli,pavan}; for(int i=0;i<4;i++) { printf(%s,names[i]); } } Here names[4][10] is a 2-D array. This means that the array names consists of 4 strings each of 10 characters length. The printf() statement displays the 4 names.

As we know all of the elements in the array store in contiguous blocks of memory. Let us see the memory organization for names array
Krishna\0 1001 Rama\0 1011 Malli\0 1021 Pavan\0 1031

As shown in the above table, the names will be stored in the addresses separated by 10 bytes. But all the names didnt occupy 10 bytes. For example, even though 10 bytes are reserved for Rama, it occupied only 5 bytes and the remaining 5 bytes will get wasted. Thus memory wastage is there for each name. This wastage can be avoided by using array of pointers to strings

http://www.academictutorials.com/c/c-string.asp http://mycblog.org/index.php?option=com_content&view=article&id=53&Itemid=72 http://www.java2s.com/Tutorial/C/0060__String/Catalog0060__String.htm

You might also like