Users Online

· Guests Online: 115

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

#C PROGRAMMING LANGUAGE TUTORIALS


Strings - C Programming

1. What is String?

Strings are arrays of characters. Each member of array contains one of characters in the string.

Example

#include<stdio.h> 
main() 
{ 
    char name[20]; 
    printf("Enter your name : "); 
    scanf("%s",name); 
    printf("Hello, %s , how are you ?\n",name); 
} 

Output Results:

Enter your name : Vineet 
Hello, Vineet, how are you ?

If user enters "Vineet" then the first member of array will contain 'V' , second cell will contain 'i' and so on. C determines end of a string by a zero value character. We call this character as NULL character and show it with \0 character. (It's only one character and its value is 0, however we show it with two characters to remember it is a character type, not an integer).

Equally we can make that string by assigning character values to each member.

name[0]='B'; 
name[1]='r'; 
name[2]='i'; 
name[3]='a'; 
name[4]='n'; 
name[5]='\0';

As we saw in above example placeholder for string variables is %s. Also we will not use a & sign for receiving string values.

2. Point to Note

While entering the string using scanf() we must be cautious about
two things:

  • The length of the string should not exceed the dimension of the character array. This is because the C compiler doesn’t perform bounds checking on character arrays.
  • scanf() is not capable of receiving multi-word strings. Therefore names such as "Vineet Choudhary" would be unacceptable. The way to get around this limitation is by using the function gets().The usage of functions gets() and its counter part puts() is shown below.
#include<stdio.h> 
main( ) 
{ 
    char name[25] ; 
    printf ("Enter your full name ") ; 
    gets (name) ; 
    puts ("Hello!") ; 
    puts (name) ; 
} 

And here is the output...

Enter your name Vineet Choudhary 
Hello! 
Vineet Choudhary

The program and the output are self-explanatory except for the fact that, puts() can display only one string at a time (hence the use of two puts() in the program above). Also, on displaying a string, unlike printf()puts() places the cursor on the next line. Though gets() is capable of receiving only one string at a time, the plus point with gets() is that it can receive a multi-word string.

If we are prepared to take the trouble we can make scanf() accept multi-word strings by writing it in this manner:

char name[25] ; 
printf ("Enter your full name ") ; 
scanf ("%[^\n]s", name) ;

Though workable this is the best of the ways to call a function, you would agree.

3. Standard Library String Functions

With every C compiler a large set of useful string handling library functions are provided in string.h file.

  • strlen - Finds length of a string
  • strlwr - Converts a string to lowercase
  • strupr - Converts a string to uppercase
  • strcat - Appends one string at the end of another
  • strncat - Appends first n characters of a string at the end of
    another
  • strcpy - Copies a string into another
  • strncpy - Copies first n characters of one string into another
  • strcmp - Compares two strings
  • strncmp - Compares first n characters of two strings
  • strcmpi - Compares two strings without regard to case ("i" denotes
    that this function ignores case)
  • stricmp - Compares two strings without regard to case (identical to
    strcmpi)
  • strnicmp - Compares first n characters of two strings without regard
    to case
  • strdup - Duplicates a string
  • strchr - Finds first occurrence ofa given character in a string
  • strrchr - Finds last occurrence ofa given character in a string
  • strstr - Finds first occurrence of a given string in another string
  • strset - Sets all characters ofstring to a given character
  • strnset - Sets first n characters ofa string to a given character
  • strrev - Reverses string

4. Example

The following example uses some of the above-mentioned functions −

#include <stdio.h>
#include <string.h>

int main () {

   char str1[12] = "Hello";
   char str2[12] = "World";
   char str3[12];
   int  len ;

   /* copy str1 into str3 */
   strcpy(str3, str1);
   printf("strcpy( str3, str1) :  %s\n", str3 );

   /* concatenates str1 and str2 */
   strcat( str1, str2);
   printf("strcat( str1, str2):   %s\n", str1 );

   /* total lenghth of str1 after concatenation */
   len = strlen(str1);
   printf("strlen(str1) :  %d\n", len );

   return 0;
}

When the above code is compiled and executed, it produces the following result −

strcpy( str3, str1) :  Hello
strcat( str1, str2):   HelloWorld
strlen(str1) :  10

5. Examples

EXAMPLE STATEMENT FOR STRING IN C LANGUAGE


1. Check whether two strings are anagrams or not


/*******************************************************
 Statement - Check whether two strings are anagrams or not
 Programmer - Vineet Choudhary
 Written For - http://developerinsider.co
 *******************************************************/

/*
 What is anagrams?
 Two words are said to be anagrams of each other if the letters from one word can be rearranged to form the other word. From the above definition it is clear that two strings are anagrams if all characters in both strings occur same number of times. For example "abc" and "cab" are anagram strings, here every character 'a', 'b' and 'c' occur only one time in both strings
 */

#include <stdio.h>

int check_anagram(char [], char []);

void main()
{
    char a[100], b[100];
    int flag;
    clrscr();
    
    printf("Enter first string\n");
    gets(a);
    
    printf("Enter second string\n");
    gets(b);
    
    flag = check_anagram(a, b);
    
    if (flag == 1)
        printf("\"%s\" and \"%s\" are anagrams.\n", a, b);
    else
        printf("\"%s\" and \"%s\" are not anagrams.\n", a, b);
    
    getch();
}

int check_anagram(char a[], char b[])
{
    int first[26] = {0}, second[26] = {0}, c = 0;
    
    while (a[c] != '\0')
    {
        first[a[c]-'a']++;
        c++;
    }
    
    c = 0;
    
    while (b[c] != '\0')
    {
        second[b[c]-'a']++;
        c++;
    }
    
    for (c = 0; c < 26; c++)
    {
        if (first[c] != second[c])
            return 0;
    }
    
    return 1;
}


2. Find a frequenct of character in string


/*******************************************************
 Statement - Find a frequenct of character in string
 Programmer - Vineet Choudhary
 Written For - http://developerinsider.co
 *******************************************************/

#include <stdio.h>
#include <string.h>
#include <conio.h>

void find_frequency(char [], int []);

void main()
{
    char string[100];
    int c, count[26] = {0};
    clrscr();
    
    printf("Input a string\n");
    gets(string);
    
    find_frequency(string, count);
    
    printf("Character Count\n");
    
    for (c = 0 ; c < 26 ; c++)
    {
        printf("%c \t  %d\n", c + 'a', count[c]);
    }
    
    getch();
}

void find_frequency(char s[], int count[]) {
    int c = 0;
    
    while (s[c] != '\0') {
        if (s[c] >= 'a' && s[c] <= 'z' )
            count[s[c]-'a']++;
        c++;
    }
}

3. Insert substring into a string

/*******************************************************
Statement - Insert substring into a string
Programmer - Vineet Choudhary
Written For - http://developerinsider.co
*******************************************************/

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
 
void insert_substring(char*, char*, int);
char* substring(char*, int, int);
 
void main()
{
   char text[100], substring[100];
   int position;
   clrscr();

   printf("Enter some text\n");
   gets(text);
 
   printf("Enter the string to insert\n");
   gets(substring);
 
   printf("Enter the position to insert\n");
   scanf("%d", &position);
 
   insert_substring(text, substring, position);
 
   printf("%s\n",text);
 
   getch();
}
 
void insert_substring(char *a, char *b, int position)
{
   char *f, *e;
   int length;
 
   length = strlen(a);
 
   f = substring(a, 1, position - 1 );      
   e = substring(a, position, length-position+1);
 
   strcpy(a, "");
   strcat(a, f);
   free(f);
   strcat(a, b);
   strcat(a, e);
   free(e);
}
 
char *substring(char *string, int position, int length) 
{
   char *pointer;
   int c;
 
   pointer = malloc(length+1);
 
   if( pointer == NULL )
       exit(EXIT_FAILURE);
 
   for( c = 0 ; c < length ; c++ ) 
      *(pointer+c) = *((string+position-1)+c);       
 
   *(pointer+c) = '\0';
 
   return pointer;
}


4. Substring from a position to length

/*******************************************************
 Statement - Substring from a position to length
 Programmer - Vineet Choudhary
 Written For - http://developerinsider.co
 *******************************************************/

#include <stdio.h>
#include <conio.h>

void main()
{
    char string[1000], sub[1000];
    int position, length, c = 0;
    clrscr();
    
    printf("Input a string\n");
    gets(string);
    
    printf("Enter the position and length of substring\n");
    scanf("%d%d", &position, &length);
    
    while (c < length) {
        sub[c] = string[position+c-1];
        c++;
    }
    sub[c] = '\0';
    
    printf("Required substring is \"%s\"\n", sub);
    
    getch();
}



5. Check if a string is a subsequence of another string


/**********************************************************
 Statement - check if a string is a subsequence of another string
 Programmer - Vineet Choudhary
 Written For - http://developerinsider.co
 **********************************************************/
 
 /*
 C program to check Subsequence, don't confuse subsequence with substring. 
 In our program we check if a string is a subsequence of another string. 
 User will input two strings and we find if one of the strings is a 
 subsequence of other. Program prints yes if either first string is a 
 subsequence of second or second is a subsequence of first. We pass smaller 
 length string first because our function assumes first string is of smaller 
 or equal length than the second string.
 */
 
#include <stdio.h>
#include <string.h>
#include <conio.h>

int check_subsequence (char [], char[]);
 
void main () {
   int flag;
   char s1[1000], s2[1000];
   clrscr();

   printf("Input first string\n");
   gets(s1);

   printf("Input second string\n");
   gets(s2);

   /** Passing smaller length string first */

   if (strlen(s1) < strlen(s2))
      flag = check_subsequence(s1, s2);
   else
      flag = check_subsequence(s2, s1);

   (flag)?printf("YES\n"):printf("NO\n");

   getch();
}

int check_subsequence (char a[], char b[]) {
   int c, d;
 
   c = d = 0;
 
   while (a[c] != '\0') {
      while ((a[c] != b[d]) && b[d] != '\0') {
         d++;
      }
      if (b[d] == '\0')
         break;
      d++;
      c++;
   }
   if (a[c] == '\0')
      return 1;
   else
      return 0;
}

/*
The logic of function is simple we keep on comparing characters of two strings, 
if mismatch occur then we move to next character of second string and if characters 
match indexes of both strings is increased by one and so on. If the first string ends 
then it is a subsequence otherwise not.
*/



6. Delete vowels from a string

/*******************************************************
 Statement - Delete vowels from a string
 Programmer - Vineet Choudhary
 Written For - http://developerinsider.co
 *******************************************************/

#include <stdio.h>
#include <string.h>
#include <conio.h>

int check_vowel(char);

void main()
{
    char s[100], t[100];
    int i, j = 0;
    clrscr();
    
    printf("Enter a string to delete vowels\n");
    gets(s);
    
    for(i = 0; s[i] != '\0'; i++) {
        if(check_vowel(s[i]) == 0) {       //not a vowel
            t[j] = s[i];
            j++;
        }
    }
    
    t[j] = '\0';
    
    strcpy(s, t);    //We are changing initial string
    
    printf("String after deleting vowels: %s\n", s);
    
    getch();
}


int check_vowel(char c)
{
    switch(c) {
        case 'a':
        case 'A':
        case 'e':
        case 'E':
        case 'i':
        case 'I':
        case 'o':
        case 'O':
        case 'u':
        case 'U':
            return 1;
        default:
            return 0;
    }
}

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.78 seconds
10,268,052 unique visits