c programming strings

C programming strings

Group of characters, digits, and symbols enclosed within quotation marks are called a string. The string is always declared as a character array. In other words, character arrays are called strings. Example: "Welcome to Balu Tutorial" Character strings are often used to build meaningful and readable programs. The common operations performed on character string are:

  • Reading and Writing strings
  • Combining strings together
  • Copying one string to another
  • Comparing strings for equality
  • Extracting a portion of a string

Declaring and Initializing Strings

A string variable is any valid C variable name and is always declared as an array. The general form of declaration of a string variable is: char string_name[size]; The size determines the number of characters in the string_name. Some examples are: 

char city[10];
char name[10];
  • A string constant is a one-dimensional array of characters terminated by a NULL (‘\0’) character. For example, char name[]={‘S’,’I’,’L’,’V’,’E’,’R’,’\0′};
  • Each character in the string occupies one byte of memory and the last character is always ‘\0’.
  • The ‘\0’ character looks like two characters, but it is actually only one character, witch the \ indicating that what follows it is something special.
  • ‘\0’ is called a NULL character. Note that ‘\0’ and ‘0’ are not the same. ASCII value of ‘\0’ is 0, whereas the ASCII value of ‘0’ is 48. The terminating NULL is important because it is the only way the functions that work with a string can know where the string ends.

C concedes the fact that you would use strings very often and hence provides a shortcut for initializing strings. For example, the string used above can also be initialized as char name[]={“SILVER”}; Note that, in this declaration ‘\0’ is not necessary. C inserts the null character automatically.

Reading Strings from Terminal

Reading Words

The familiar input function scanf( ) can be used with %s format specification to read in a string of characters.

char name[10];

scanf(“%s”,name);

The problem with scanf() function is that it terminates its input on the first white space it finds. (A white space includes blanks, tabs, carriage returns, form feeds, and new lines.) Therefore, if the following line of text is typed in at the terminal, for example, if we enter a string Balu Tutorial then only the string “Balu” will be read into the string name.

Since the blank space after the word “Balu” will terminate the string. Note that unlike previous scanf() calls, in the case of character arrays, the ampersand (&) is not required before the variable name.

The scanf() function automatically terminates the string that is read with a NULL character and therefore the character array should be large enough to hold the input string plus the NULL character.

If we want to read the entire line “Balu Tutorial”, then we may use two character array of appropriate sizes. That is,

char name1[10];

char name2[10];

scanf(“%s%s”,name1,name2);

with the line of text, Balu Tutorial will assign the string “Balu” to name1 and “Tutorial” to name2.

Reading a Line of Text

In many texts processing application, we need to read in an entire line of the text from the terminal. It is not possible to use scanf() function to read a line containing more than one word. This is because the scanf() terminates reading as soon as space is encountered in the input.

We can read a line of text by using getchar or gets functions. By using the getchar function we can read a single character from the terminal. We can use this function repeatedly to read successive single characters from the input and place them into a character array. Thus, an entire line of text can be read and stored in an array.

The reading is terminated when the newline character (‘\n’) is entered and the NULL character is then inserted at the end of the string. The function scanf() is not capable of receiving multi-word strings. Therefore, names such as “Balu Tutorial” would be unacceptable.

The way to get around this limitation is by using the function gets(). Putting String on screen: We have used extensively the printf() function with %s format to print strings to screen.

The format %s can be used to display an array of character that is terminated by NULL character. For example, the statement printf(“%s”,name); Can be used to display the entire contents of the string name. We can also specify the precision with which the string is displayed. For instance, the specification %10.4 indicates that the first four characters are to be printed in a field width of 10 columns. However, if we include the minus sign in the specification (e.g., %-10.4), the string will be printed left justified.

For printing the string on the screen we can use another function is called puts. the fact that puts( ) can display only one string at a time. Also, on display a string, unlike printf( ), puts( ) places the cursor on the next line.

String formats with different precision

#include <stdio.h>
int main()
{
   char text[15]="BALU TUTORIAL";
   printf("%s\n",text); //BALU TUTORIAL
   printf("%.5s\n",text); //BALU
   printf("%.8s\n",text); //BALU TUT
   printf("%.15s\n",text); //BALU TUTORIAL
   printf("%-10.4s\n",text); //BALU
   printf("%11s\n",text); //BALU TUTORIAL

   return 0;
}

String standard functions

The “C” library provides a large number of string handling functions that can be used for performing string manipulations. These functions are available in the file string.h. This header file is used or included whenever these functions are used.

FunctionsDescription
strlen()Determines length of a string.
strcpy()Copies a string from source to destination.
strncpy()Copies characters of a string to another string upto the specified length.
strcmp()Copies characters of a string to another string up to the specified length.
stricmp()Compares two strings. (NOTE: ignore case)
strncmp()Compares characters of two strings upto the specified length.
strnicmp()Compares characters of two strings upto the specified length. Ignores cases.
strlwr()Converts uppercase characters of a string to lowercase
strupr()Converts lowercase characters of a string to uppercase.
strdup()Duplicates a string.
strchr()Determines the first occurrence of a given character in a string.
strrchr()Determines the last occurrence of a given character in a string.
strstr()Determines first occurrence of a given string in another string.
strcat()Appends source string to destination string
strncat()Appends source string to destination string up to the specified length.
strrev()Reverses all characters of a string.
strset()Sets all characters of a string with a given argument or symbol
strnset()Sets specified numbers of characters of a string with a given argument or symbol.
strspn()Finds up to what length two strings are identical.
strpbrk()Searches the first occurrence of the character in a given string and then it displays the string starting from that character.

strcpy() Example

#include <stdio.h> 
#include <string.h> 
int main() 
{ 
  char ori[20],dup[20]; 
  printf("Enter Your Name:"); 
  gets(ori); 
  strcpy(dup,ori); 
  printf("original string:%s",ori); 
  printf("\nduplicate string:%s",dup); 
 
   return 0;
 }

Output:

Enter Your Name:Balu Tutorial
original string:Balu Tutorial
duplicate string:Balu Tutoria

strupr() Example

#include <stdio.h>
#include <string.h>
int main()
{
   char upper[20];
   printf("Enter Your Name:");
   gets(upper);
   printf("Upper case:%s", strupr(upper));

   return 0;
}

Output:

Enter Your Name:balu tutorial

Upper case: BALU TUTORIAL

whatsapp

error: Content is protected !!