Unit-3 : Strings

definition

The string can be defined as the one-dimensional array of characters terminated by a null (‘\0’). The character array or the string is used to manipulate text such as word or sentences. Each character in the array occupies one byte of memory, and the last character must always be 0 .

declaration

There are two ways to declare a string in c language.

  1. By char array
  2. By string literal

Let’s see the example of declaring string by char array in C language.

  1. char ch[10]={‘j’, ‘a’, ‘v’, ‘a’, ‘t’, ‘p’, ‘o’, ‘i’, ‘n’, ‘t’, ‘\0’};  

As we know, array index starts from 0, so it will be represented as in the figure given below.

C Array

While declaring string, size is not mandatory. So we can write the above code as given below:

  1. char ch[]={‘j’, ‘a’, ‘v’, ‘a’, ‘t’, ‘p’, ‘o’, ‘i’, ‘n’, ‘t’, ‘\0’};  

We can also define the string by the string literal in C language. For example:

  1. char ch[]=”javatpoint”;  

In such case, ‘\0’ will be appended at the end of the string by the compiler.

Initializing String [Character Array] :

Whenever we declare a String then it will contain garbage values inside it. We have to initialize String or Character array before using it. Process of Assigning some legal default data to String is Called Initialization of String. There are different ways of initializing String in C Programming –

  1. Initializing Unsized Array of Character
  2. Initializing  String Directly
  3. Initializing  String Using Character Pointer

Way 1 : Unsized Array and Character

  1. Unsized Array : Array Length is not specified while initializing character array using this approach
  2. Array length is Automatically calculated by Compiler
  3. Individual Characters are written inside Single Quotes , Separated by comma to form a list of characters. Complete list is wrapped inside Pair of Curly braces
  4. Please Note : NULL Character should be written in the list because it is ending or terminating character in the String/Character Array
char name [] = {'P','R','I','T','E','S','H','\0'};

Way 2 : Directly initialize String Variable

  1. In this method we are directly assigning String to variable by writing text in double quotes.
  2. In this type of initialization , we don’t need to put NULL or Ending / Terminating character at the end of string. It is appended automatically by the compiler.
char name [ ] = "PRITESH";

Way 3 : Character Pointer Variable

  1. Declare Character variable of pointer type so that it can hold the base address of “String”
  2. Base address means address of first array element i.e (address of name[0] )
  3. NULL Character is appended Automatically
char *name = "PRITESH";

standard library function

C supports a large number of string handling functions in the standard library "string.h".

Few commonly used string handling functions are discussed below:

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

Strings handling functions are defined under "string.h" header file.

#include <string.h>

gets() and puts()

Functions gets() and puts() are two string functions to take string input from the user and display it respectively as mentioned in the previous chapter.

#include<stdio.h>int main(){    char name[30];    printf("Enter name: ");    gets(name);     //Function to read string from user.    printf("Name: ");    puts(name);    //Function to display string.    return 0;}

Note: Though, gets() and puts() function handle strings, both these functions are defined in "stdio.h" header file.

1. strlen( ) Function

This function counts the number of characters present in a string. Its usage is illustrated in the following program.

Program to demonstrate strlen() function

char  arr[ ] = “Generalnote” ;
int  len1, len2 ;
len1 = strlen ( arr ) ;
len2 = strlen ( “C Tutorial” ) ;
printf(” \nstring = %s length = %d “,  arr, len1) ;
printf(” \nstring = %s length = %d “,  “C Tutorial”, len2) ;
return ( 0 ) ;
}

Output :

string = Generalnote length = 11
string = C Tutorial length = 10

In the first call to the function strlen( ), we are passing the base address of the string, and the function in turn returns the length of the string. While calculating the length it doesn’t count ‘\0’.

2.strcpy( ) Function

This function copies the contents of one string into another. The base addresses of the source and target strings should be supplied to this function.

Program to demonstrate strcpy() function

\* C Program to demonstrate strcpy() function *\

# include < stdio.h >
int  main( )
{

char  source[ ] = “General note” ;
char  target[25] ;
strcpy(  target, source) ;
printf(” \nsource string = %s “,  source) ;
printf(” \ntarget string = %s “,  target) ;
return ( 0 ) ;
}

Output :

source string = Generalnote
target string = Generalnote

On supplying the base addresses, strcpy( ) goes on copying the characters in source string into the target string till it doesn’t encounter the end of source string (‘\0’). It is our responsibility to see to it that the target string’s dimension is big enough to hold the string being copied into it. Thus, a string gets copied into another, piece-meal, character by character.

3.strcat() function

This function concatenates the source string at the end of the target string.

Program to demonstrate strcpy() function

\* C Program to demonstrate strcpy() function *\

# include < stdio.h >
int  main( )
{

char  source[ ] = “General” ;
char  target[30] = “Note” ;
strcat(  target, source) ;
printf(” \nsource string = %s “,  source) ;
printf(” \ntarget string = %s “,  target) ;
return ( 0 ) ;
}

Output :

source string = General
target string = GeneralNote

4.strcmp( ) Function

This is a function which compares two strings to find out whether they are same or different. The two strings are compared character by character until there is a mismatch or end of one of the strings is reached, whichever occurs first. If the two strings are identical, strcmp( ) returns a value zero. If they’re not, it returns the numeric difference between the ASCII values of the first non-matching pairs of characters.

Program to demonstrate strcmp() function

\* C Program to demonstrate strcmp() function *\

# include < stdio.h >
int  main( )
{

char  string1[ ] = “General” ;
char  string2[ ] = “Note” ;
int  i, j, k ;
i = strcmp(  string1, “General”) ;
j = strcmp(  string1, string2) ;
k = strcmp(  string1, “General Note”) ;
printf(” \n %d %d %d “,  i, j, k) ;
return ( 0 ) ;
}

Output :

0   6   -32

implementation without using standard library functions

1.Calculate Length of String without Using strlen() Function

#include <stdio.h>

int stringLength(char*);

int main()
{
 char str[100]={0};
 int length;

 printf("Enter any string: ");
 scanf("%s",str);
 
 length=stringLength(str);
 
 printf("String length is : %d\n",length);

 return 0;
}

int stringLength(char* txt)
{
 int i=0,count=0;
 
 while(txt[i++]!='\0'){
 count+=1;
 }
 
 return count;
}

Output

Enter any string: IncludeHelp 
String length is : 11

2.C Program to Copy One String into Other Without Using Library Function.

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.   int c = 0;
  6.   char s[1000], d[1000] = “What can I say about my programming skills?”;
  7.  
  8.   printf(“Before copying, the string: %s\n“, d);
  9.  
  10.   printf(“Input a string to copy\n“);
  11.   gets(s);
  12.  
  13.   while (s[c] != ‘\0‘) {
  14.     d[c] = s[c];
  15.     c++;
  16.   }
  17.  
  18.   d[c] = ‘\0‘;
  19.  
  20.   printf(“After copying, the string: %s\n“, d);
  21.  
  22.   return 0;
  23. }

Output of the program:

  1. Before copying, the string: What can I say about my programming skills?
  2. Input a string to copy
  3. My programming skills are improving.            
  4. After copying, the string: My programming skills are improving.