C Programming | String Functions
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 )
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);
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.
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.
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);
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)); }
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
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] = ''; }
NICE. chitasmitablog.com
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!
Thanks @Hairstyles. We will post regularly on C Programming, though we don’t have huge readers’ base, but we are improving.
Glad to find something technical over here on WordPress, I would be looking forward to collaborate with you in creating highly advanced tutorials for my site
Excellent web site you have got here.. It’s hard to find high quality writing like yours these days. I honestly appreciate people like you! Take care!!
Hey very nice website!! Man .. Beautiful .. Amazing .. I’ll bookmark your website and take the feeds also…I am happy to find so many useful information here in the post, we need develop more techniques in this regard, thanks for sharing. . . . . .
Hello! I’m at work surfing around your blog from my new iphone 3gs! Just wanted to say I love reading your blog and look forward to all your posts! Keep up the superb work!
I simply wished to thank you very much once again. I am not sure the things that I might have created in the absence of the actual pointers shown by you directly on this problem. Previously it was a very fearsome problem for me, nevertheless being able to view this professional form you processed that took me to leap over happiness. Extremely thankful for your support as well as wish you are aware of a powerful job you have been getting into teaching many people with the aid of your web page. Probably you haven’t met all of us.