C Programming | String Functions

Posted by

Advertisements


What we would learn

  • String Functions ( strlen, strcpy, strncpy, strcmp, strncmp, strcat, strncat, strchr, strrchr, strstr, strspn, strcspn, strtok )
  • Reading from/Printing to Strings ( sprintf, sscan )
Advertisements

Processing Character Strings

There exists a set of C library functions for character string manipulation.

  • strcpy :: string copy
  • strlen :: string length
  • strcmp :: string comparison
  • strtcat :: string concatenation

It is required to add the line

#include <string.h>

1. strcpy()

Works very much like a string assignment operator.

char *strcpy (char *str1, char *str2);
  • Assigns the contents of str2 to str1.
  • Returns address of the destination string.

Examples:

strcpy (city, “Calcutta”); 
strcpy (city, mycity);

Warning:

  • Assignment operator do not work for strings.
city  =  “Calcutta”; // INVALID

2. strlen()

Counts and returns the number of characters in a string.

intstrlen(char *str);

Example:

len = strlen (string); /* Returns an integer */
  • The null character (‘\0’) at the end is not counted.
  • Counting ends at the first null character.
char  city[15]; int  n; 
strcpy (city, “Calcutta”); 
n = strlen (city);
Advertisements

3. strcmp()

Compares two character strings.

int strcmp(char *str1, char *str2); 
  • Compares the two strings and returns 0 if they are identical; non-zero otherwise.

Examples:

if (strcmp(city, “Delhi”) == 0) {  
// Do some task
} 
if (strcmp(city1, city2) != 0) { 
// Do some task
}

Actually, the function returns the difference in ASCII values of the first letter of mismatch.

Advertisements

Less than 0

  • If the ASCII value of the character they differ at is smaller for str1, or str2 is longer than str1

Greater than 0

  • If the ASCII value of the character they differ at is greater for str1, or str1 is longer than str2

Equal to 0

  • If the two strings are identical

Please fill the feedback form whose link is given below to help us to improve. We would love to get suggestions from you for better results of this site.

https://forms.gle/r5fJjWmkqtdLVJr48

String Comparison

strcmp examples:

strcmp(“hello”,”hello”);   //returns 0 
strcmp(“yello”,”hello”);   // returns value > 0 
strcmp(“Hello”,”hello”);  //returns value < 0 
strcmp(“hello”,”hello there”);  //returns value < 0 
strcmp(“some diff”,”some dift”);  //returns value < 0

expression for determining if two strings s1, s2 hold the same string value:

! strcmp(s1, s2)

Sometimes we only want to compare first n chars:

int strncmp(char *s1, char *s2, intn);
/*Works the same as strcmp except 
that it stops at the nth character */
  • looks at less than n characters if either string is shorter than n
strcmp(“some diff”,”some DIFF”); //returns value > 0 
strncmp(“some diff”,”some DIFF”,4); //returns 0

String Comparison (ignoring case)

int strcasecmp(char *str1,  char *str2);
/*  similar to strcmp except that
upper and lower case characters 
(e.g., ‘a’ and ‘A’) are considered to be equal */

int strncasecmp(char *str1, char *str2,  int n);
/* version of strncmp that ignores case */

4. strcat()

Joins or concatenates two strings together

char *strcat (char *str1, char *str2); 
  • str2 is appended to the end of str1.
  • The null character at the end of str1 is removed, and str2 is joined at that point.
  • str1 should have enough space — Programmer’s responsibility

Example:

strcpy(name1, “Amit ”); 
strcpy(name2, “Roy“); 
strcat(name1, name2);
Advertisements

Example :: count uppercase

/* Read a line of text and count the number of uppercase letters */ 
#include  <stdio.h> 
#include  <string.h> 
main() { 
  char  line[81]; 
  int  i, n, count=0; 
  scanf (“%[^n]”, line); 
  n = strlen (line); 
  for (i=0; i<n; i++) 
    if (isupper(line[i]) 
      count++; 
  printf (“n The number of uppercase letters in the string %s is %d”, line, count); 
}

Example :: compare two strings

#include <stdio.h> 
int my_strcmp(char s1[ ],char s2[ ]) { 
  int i=0; 
  while(s1[i]!='' && s2[i]!=''){ 
    if(s1[i]!=s2[i]) 
      return(s1[i]-s2[i]); 
    else i++; 
  } 
  return(s1[i]-s2[i]); 
}

main() { 
  char string1[100],string2[100]; 
  printf("Give two strings n"); 
  scanf("%s%s",string1,string2); 
  printf("Comparison result: %d n", 
  my_strcmp(string1,string2)); 
}
Advertisements

If you want to know briefly about character strings in C language then it is recommended to read this article : C Programming | Character Strings

Searching for a Character/String

char *strchr(char *str, int ch);
  • returns a pointer (char *) to the first occurrence of chin str
  • returns NULL if chdoes not occur in str
  • can subtract original pointer from result pointer to determine which character in array is ch
char *strstr(char *str, char *searchstr)
  • similar to strchr, but looks for the first occurrence of the string searchstrin str
char *strrchr(char *str, int ch)
  • similar to strchrexcept that the search starts from the end of string strand works backward

Printing to a String

  • The sprintf function allows us to print to a string argument using printf formatting rules
  • First argument of sprintf is the string to print to, remaining arguments are as in printf

Example:

char buffer[100]; 
sprintf (buffer, ”%s, %s”, LastName, FirstName); 
if (strlen(buffer) > 15) 
  printf(“Long name %s %sn”, FirstName, LastName);

Reading from a String

  • The sscanf function allows us to read from a string argument using scanf rules
  • First argument of sscanf is the string to read from, remaining arguments are as in scanf
Advertisements

Example:

char buffer[100] = “A10 50.0”; 
sscanf (buffer,”%c%d%f”, &ch, &inum, &fnum); 
/* puts ‘A’ in ch, 10 in 
inum and 50.0 in fnum*/

Example :: Duplicate Removal

Write a C function that takes a string as an argument and modifies the string so as to remove all consecutive duplicate characters, e.g., mississippi-> misisipi.

void remove_duplicates(char word[ ] ) { 
    int k, j; 
    char prev = ''; 
    for (k = j = 0; word[k]!=''; k++)  { 
      if (prev != word[k]) 
        word[j++]=word[k]; 
     prev = word[k]; 
    } 
    word[j] = ''; 
}
Advertisements

Feel free to fill this feedback form to help us improve our content

https://forms.gle/r5fJjWmkqtdLVJr48

Thanks for reading this article,

Team BloggerBoy.


We hope that you have found this article valuable. Please visit some of our recent post to gain lots of information. And feel free to share them with your friends and family.

6 comments

  1. magnificent post, very informative. I wonder why the other specialists of this sector don’t notice this. You should continue your writing. I am sure, you have a huge readers’ base already!

    Like

Leave a Reply to Kunal Jayswal Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s