Strings in C

In C programming, a string is a sequence of characters terminated with a null character \0. 

For example: 

         char c[ ] = "c string"; 

When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character \0 at the end by default.






String:

  • A string is a sequence of characters that treated as a single data item.
  • The string is defined between double quotation mark.

 Example: “ I teach C language” 

List of strings operation:

• The operations performed on strings are follows: 

  1.  Reading and Writing strings 
  2.  Combining string together 
  3.  Comparing two strings 
  4.  Copying one string to another 

Declaration and initialization of string: 


• C does not support string as data type, so to declare string variable character array is used.

• Declaration of String: 

             char string_name[size]; 

 Here the size determines the number of character in string_name. 

• Example : 

               char city[10]; 

 When the compiler assigns a character string to character array, it automatically supplies null character(‘\0’) at the end of string. Therefore the size should be equal to maximum number of characters in string plus one.


• Initialization of string: 


                  char city[9] = ’’NEW YORK”; 
                  char city[9] = {‘N’,’E’,’W’,’ ’,’Y’,’O’,’R’,’K’,’\0’}; 
                  char city[]=”NEW YORK”;
  • We can also declare the size larger than the string size in the initialize. char city[20]=”NEW YORK”;  We cannot declare the size smaller than the string size in the initialize. char city[5]=”NEW YORK”;               this will result in a compile time error. 

  • We cannot separate the initialization from declaration. char city[9]; city = “NEW YORK”; 

         it is not allowed.

  •  Declaring and initializing string variables
                 char string_name[size]; 
  •  Reading strings from terminal
                 scanf(“%s”, string_name); 
                 gets(string_name); 
                 getchar(); 
  •  Printing strings to terminal 
                 printf (“%s”, string_name); 
                 puts(string_name); 
                 putchar(char_name);

Reading strings from the user:

scanf() function: 

  • Input function scanf is used with %s format specification to read string. 
          Example : char city[9];

                           scanf(“%s”,city);

  •  The problem with scan function is that it terminates reading on the first white space it finds. 
  •  A white space includes blanks, tabs, carriage returns and new lines. 
  • Example : If the NEW YORK is input then only “NEW” will be read, because the blank space after the word NEW will terminate the reading of string. 
  • We can also specify the field width using the form %ws in the scanf statement for reading a specified number of characters from the input string.

getchar and gets functions : 

getchar() 

  • getchar is the function to read a single character from the terminal.
  • The reading is terminated when the new line character (‘\n’) is entered and the null character is then inserted at the end of the string. char ch; ch = getchar( );
  • getchar function has no parameters


gets()

  • gets is the function to read characters into string from the terminal. 
  • gets is the library function and available in header file.
  • The gets function called as under : gets(str);
  • where str is the string variable.
  • The reading is terminated when the new line character (‘\n’) is encountered and the null character is then inserted at the end of the string.
  • gets function has one parameter.


Writing strings from terminal 

printf function:

 • Output function printf is used with %s format specification to write string. 
 Example : 
                 printf(“%s”, name);

putchar and puts functions :


putchar 

  •  putchar is the function to print the values of character variables.
  •  It takes the following form : char ch = ‘A’; putchar(ch) 
  •  The function putchar has one parameter.
  •  We can use this function repeatedly to print a string of characters stored in array using a loop. 
  •  Example : 
        char name = “VINAYAK INFOTECH”;
            for (i=0; i<=5; i++) 
        { 
           putchar(name[i]);
        }


puts functions

  • puts is the function to print the values of string variables. 
  • puts is the library function and available in header file. 
  • The puts function called as under : puts(str); 
  • where str is the string variable. 
  • puts function has one parameter. 
  • Example : 
                  char line[80]; 
                  gets(line); 
                  puts(line); 
  • This example read a line of text from the keyboard and displays it on the screen.

String Handling Functions or Built-in String Functions or String Manipulation Functions:

Function    Work of Function 
  • strlen() computes string's length 
  • strcpy() copies a string to another
  • strcat() concatenates(joins) two strings
  • strcmp() compares two strings 

C strlen()

The strlen() function calculates the length of a given string.

  • The strlen() function takes a string as an argument and returns its length. The returned value is of type size_t (the unsigned integer type). 
  • It is defined in the <string.h> header file. 
  • Example: C strlen() function
 #include <stdio.h>
 #include <string.h>
       int main() 
  {
      char a[20]="Program"; 
      char b[20]={'P','r','o','g','r','a','m','\0'};
    // using the %zu format specifier to print size_t
    printf("Length of string a = %zu \n",strlen(a)); 
    printf("Length of string b = %zu \n",strlen(b));
    return 0; 
 } 

Output:

 Length of string a = 7 
 Length of string b = 7 

Note that the strlen() function doesn't count the null character \0 while calculating the length.


 C strcpy()


  • The function prototype of strcpy() is:

              char* strcpy(char* destination, const char* source); 

  • The strcpy() function copies the string pointed by source (including the null character) to the destination. 
  • The strcpy() function also returns the copied string. 
  • The strcpy() function is defined in the string.h header file. 

Example:  C strcpy()

 #include <stdio.h>
 #include <string.h>
 int main() 
{
 char str1[20] = "C programming";
 char str2[20]; 
// copying str1 to str2 strcpy(str2, str1); 
puts(str2); 
// C programming return 0; 
}

 Output:

 C programming 

Note: When you use strcpy(), the size of the destination string should be large enough to store the copied string. Otherwise, it may result in undefined behavior.


 C strcat()

 In C programming, the strcat() function contcatenates (joins) two strings.
 The function definition of strcat() is: 
          char *strcat(char *destination, const char *source) 
It is defined in the string.h header file. 

strcat() arguments:

As you can see, the strcat() function takes two arguments: 

destination - destination string 
source - source string 

The strcat() function concatenates the destination string and the source string, and the result is stored in the destination string. 

Example: C strcat() function 

#include <stdio.h>
 #include <string.h>
 int main() 
char str1[100] = "This is ", str2[] = "quickcodings.blogspot.com"; 
// concatenates str1 and str2
 // the resultant string is stored in str1. 

  strcat(str1, str2); 
  puts(str1);
  puts(str2); 
  return 0;
  } 
  
  Output:

  This is quickcodings.blogspot.com 
  quickcodings.blogspot.com

  Note: When we use strcat(), the size of the destination string should be large enough to store the resultant string. If not, we will get the segmentation fault error.


 C strcmp()

The strcmp() compares two strings character by character. If the strings are equal, the function returns 0. 

C strcmp() Prototype

 The function prototype of strcmp() is:

     int strcmp (const char* str1, const char* str2); 

strcmp() Parameters 

The function takes two parameters: 

  • str1 - a string
  • str2 - a string 

Return Value from strcmp() 

      Return    Value Remarks 
  •   0                 if strings are equal 
  • non-zero         if strings are not equal 

The strcmp() function is defined in the string.h header file.

 Example: C strcmp() function

 #include <stdio.h> 
#include <string.h>
 int main() 
{
 char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd"; int result;
 // comparing strings str1 and str2 result = strcmp(str1, str2)
printf("strcmp(str1, str2) = %d\n", result); 
// comparing strings str1 and str3 result = strcmp(str1, str3); 
printf("strcmp(str1, str3) = %d\n", result); 
return 0; 

Output:

 strcmp(str1, str2) = 1 
 strcmp(str1, str3) = 0 

In the program, 
  • strings str1 and str2 are not equal. 
  • Hence, the result is a non-zero integer. strings str1 and str3 are equal. Hence, the result is 0.

Post a Comment

0 Comments