Header Ads

Strings



A character is a single alphabet, number, punctuation mark, or other such symbol. A string is any sequence of characters. Strings are used to hold text data, which is comprised of characters. Characters and strings are very useful in many programming applications. We are treating the strings separately, because dealing with strings has its own flavor.

Declaration and Initialization of Strings

A string is an array of characters and is enclosed within a pair of double quotes. Double quotes do not form the part of a string. Since the string can be of any length, the end of the string is marked with a null character (denoted by '\0'). The null character is a byte with all bits off; hence its ASCII value is zero. The character arrays (strings) are declared in a similar manner as we had declared any other numeric array

Syntax for declaring a character array - char array-name [size]

For example, we want to store the string “MY YAHOO”. For this purpose, we need to define a character array of nine elements. The size of the string must include the storage needed for null character.
Declaring char array
To store this string, we have to declare the array as:                      char str[9];

To store 60 student names, we need to declare two-dimensional character array as:

            char names[60][25];      /* array size: 60 rows x 25 columns */

Each name can hold a maximum of 25 characters (the actual name should be less than or equal to 24 characters and one character is left to store null character).

Initialization of Strings

Strings can be initialized at the time of declaration or using a for-loop in the program. The string can be initialized in any one of the following ways:

(a) char str[9] = "MY YAHOO";
(b) char str[9] = { 'M', 'Y', ' ', 'Y''A', 'H', '0', '0', '\0' };
(c) char str[] = "MY YAHOO";
(d) char str[] = { 'M''Y', ' ', 'Y''A''H''0''0''\0' }

In declarations (a) and (c), a group of characters are enclosed within double quotes. In declarations (b) and (d), each character is included in a pair of single quotes and separated by commas. In the first two declarations the size of the string is specified, whereas the string size is optional (empty brackets) as illustrated in (cand (d) declarations.

When we define the maximum string size, the compiler allocates the specified number of member locations to store the string. In case, the number of characters of the string is more than the maximum string size, the compiler gives the error message as "too many initializers". The following definition illustrates this

            char str[10]="VISUAL BASIC"                      /* Compilation error *

If the number of characters of the string is less than the maximum string size, then string is terminated by the null character and the remaining characters will be ignored. The following example demonstrates this definition.

           char str[12] = "DATABASE";

Database string array
A declaration like char str[ ]; is invalid because array size is not included in the brackets. It is only valid with initialization. Similarly, the string cannot be assigned a value using assignment operator like 

              char str[10];                    /* Valid declaration */  
              str="ABCDE";               /*Invalid assignment */

The above statement would result in error

Reading and Writing Strings - The strings can be read in one of the following ways

Using getchar() function, we can read character by character and store the string in a character array. The following program illustrates the use of getchar() function to accept the string from the keyboard

Code

#include <stdio.h> 
void main() 
{ 
    char str[25], ch; int i = 0; 
    while((ch = getchar()) != '\0' ) /* Input a char and assign it to ch until enter key is pressed*/ 
     { 
        str[i] = ch;		/* Assign ch to str[i] */ 
        i++; 			    /* Increment i by 1 */ 
      } 
              str[i] = '\0';   /* Terminate the string by null char * 
    puts(str);   		 /* Display the string */ 
}
(a) scanf() function is used to accept a string from the keyboard by using format specifier "%s".

Code

#include <stdio.h> 
void main() 
{ 
 char str[25]; 
 scanf("%d", &str); /* Read the string */ 
 printf("%s", str);  /* Display the string */ 
} 
The str is a character array. The disadvantage of using scanf to input string is that we cannot embed spaces into the string. As soon as the scanf encounters space in the input string, input is terminated and the remaining part of the string is ignored. For example, we want to input the string "MY YAHOO", scanf will only store "MYin the string, the "YAHOO" is ignored. The scanf can be used to read a string, which contains continuous sequence of characters without white spaces.

(b) gets() function is also used to input strings from the keyboard. The syntax of gets() function is
                
                         gets(string)

The advantage of gets() function over scanf() function is that, with the gets(), we can also read white spaces from the keyboard and store the entire string. To test gets() function, replace scanf() in the Program with gets (str) and execute the program. The gets() and scanf() functions automatically add null character to end of the string

(c) puts() function is used to display the string on the standard output device (monitor). The syntax of puts() function is 

                     puts(string)

puts() function differs from printf() function in the way that puts() function automatically puts a new line character `\n' after display of each string, whereas we have to specify the '\n' in the format specifier of printf(function. The puts() function can handle only one string at a time

Arrays of Strings 

A string is a one-dimensional array of characters. We can store one string in an array. To store multiple strings, we have to use two-dimensional character arrays. Each row would contain one string. Following is an example of two-dimensional character array, which is initialized with student names. Each string is automatically terminated with a null character. In this array, we can store five names and each name can hold a maximum of 10 characters, including the null character.

            char name[5][10] = { "JOHN PAUL", "AMYA", "KIRAN”, “RAFI", "RAM MOHAN" };

The above declaration will create a two-dimensional array as shown below.
Two dimensional array
Using for-loop, we can print the names. First subscript is sufficient to reference the string (each row of the table of names)

            for (i = 0; < 5;++)
           {
                 puts (name[i]);
           }

String Function 

1. strcmp( ) function - This function is used to check whether two strings are same or not. If  both the strings are same it return a 0 or else it returns the numeric difference between the ASCII values of  non- matching characters e.g. the following program 

Code

#include <stdio.h> 
void main() 
{
  char string1 [ ]="orange": 
  char string2 [ ]="banana": 
  printf("%d\n", strcmp(string1, string2)); 
  printf(“%d\n", strcmp(string2. "banana"); 
  printf("%d", strcmp(string1, "Orange")); 
}
Output
13
0
32

In the first printf statement we use the strcmp( ) function with string1 and string 2 as it arguments. As both  are not equal (same) the function strcmp( ) returned 13, which is the numeric difference between “orange” and "banana" i.e, between string and string2.
In the second printf statement the arguments to strcmp( ) are string2 and "banana". As string2 represents "banana", it will obviously return a 0.
In the third printf statement strcmp( ) has its arguments "orange" and "Orange" because string1 represents "Orange". Again a non-zero value is returned as "orange" and "Orange" are not equal. 

2. strcpy( ) function -- The function copies one string to another for e.g. the following program 

Code

#include <stdio.h> 
#include <string.h> 
void main() 
{
  char source [ ] = "orange"; 
  char target [20]; 			
  strcpy(target, source); 
  printf(source: %s\n", source); 
  printf(target:%s", target); 
}
Output
source : orange
target  : orange

3. strcat( )-- This function concatenates the source string at the end of the target string for e.g, "Bombay” and "Nagpur" on concatenation would result in to a string "Bombay Nagpur". Refer the following example - 

Code

#include <stdio.h> 
#include <string.h> 
void main() 
{ 
   char source []= "Folks"; char                               
   target [30] = "Hello"; 
   strcat(target, source); 
   printf("\n source string = %s", source); 
   printf("\n target string = %s", target); 
}
Output
source string = folks
target string = Hello folks

4. strlen( ) - This function counts the number of characters present in a string.

Code

#include <stdio.h> 
#include <string.h> 
void main() 
{ 
  char arr[ ] = "Bamboozled"
  int len1, len 2; 
  len1 = strlen(arr);
  len2 = strlen("Hunpty Dumpty");
  printf("\n string = %s length = %d", arr, len 1); 
  printf("\n string = %s length = %d", "Humpty Dumpty", len2);
}
Output
string = Bamboozled  length=10
string = Humpty Dumpty length = 13
while calculating the length of the string it does not count '\0'

5. strrev( ) - This function reverses the string.

Example 

Code

#include<stdio.h> 
#include <string.h> 
void main( ) 
{
   char string[]="spark"; 
   strrev (string); 
   printf("reverse string is %s", string); 
} 
Output: reverse string is kraps 

6. strcmpi (string 1, string2) - This function is similar to strcmp(). The only difference is that it ignores case Uppercase and lowercase character consider same.

Example "SparK" and "spark" both are same

Code

#include <stdio.h> 
#include <string.h> 
void main() 
{ 
   char string[]="spark",string2[]="SPArk"; 
   int cmp; 
   cmp=strcmpi(string 1,string2); 
   if(cmp>0) 
     printf("%s > %s", string1,string2); 
   else 
   { 
     if(cmp<0) 
        printf("%s<%s",string 1,string2); 
     else 
        printf("%s=%s",string1,string2); 
   }
}
Output: spark SPArk.

7) strlwr (string): This function accepts single string that can be in any case(lower or upper)It converts the string in lower case.

Example 

Code

#include <stdio.h> 
#include <string.h> 
void main() 
{ 
   char string1[ ]="SPArk"; 
   strlwr(string1); 
   printf("%s is in lower case", string1); 
}
Output: spark is in lower case

8) strupr (string) - This function accepts single string that can be in any case(lower or upper). It converts the string in upper case shown in following example

Code

#include <stdio.h> 
#include <string.h> 
void main() 
{ 
   char string1[ ]="SPArk"; 
   strupr(string1); 
   printf("%s is in upper case",string1); 
} 
Output: SPARK is in upper case.

9) char* strstr (main string, substring): This function accepts two strings i.e main string and substring. It searches for the first occurrence substring in main string and returns the character pointer to the first char.
Example

Code

#include <stdio.h> 
#include <string.h> 
void main( ) 
{
  char str1[]="programmingspark", str2[]= "ming", *ptr; 
  ptr = strstr(strl, str2); 
  printf("substring is: %s", ptr); 
  getch(); 
}
Output: substring is mingspark 

No comments

Powered by Blogger.