In C language, a string is a character treated as one unit. Virtually all strings are treated as a variable length piece of data.
For example one of the most common of all strings is a name. Names vary by nature, by length and it makes no difference.
Given that we have the data that can vary in size, and how we accommodate them in our programs.
The fixed-length string can be stored easily as we know the length of the string.
Variable length strings can contain non-data characters such as spaces and end of the line etc.,
Length-controlled strings add a count that specifies the number of characters in the strings. Another technique used to identify the end of the string is the delimiter.
String manipulation in C language
In C language, the group of characters, digits, and symbols enclosed within quotation marks are called as strings otherwise strings are an array of characters.
The null character (“\0”) is used to mark the end of the string.
Example :
char name[ ]={‘B’, ‘A’, ‘B’, ‘U’, ‘\0’};
Each character is stored in one byte of memory and successive characters of the string are stored in a successive byte.
The variables that can hold more than a single character, are precisely where the array of characters comes into the picture.
Example
char word[ ]={ ‘C’, ‘O’, ‘M’ , ‘P’, ‘U’, ‘T’, ‘E’, ‘R’};
Remembering that in the nonappearance of array size, the C compiler automatically computes the number of elements in the array based upon the number of characters initialized, this statement reserves space in memory for exactly eight characters, as shown below.
word [0] ‘C‘
word[1] ‘O‘
word[2] ‘M‘
word[3] ‘P‘
word[4] ‘U‘
word[5] ‘T‘
word[6] ‘E‘
word[7] ‘R‘
The Array in Memory
Character arrays are special. They have certain initialization properties not shared with other array types because of their relationship with strings, Of course, character arrays can be initialized in the normal way using an initializer list.
char letters[ ] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’}
But they may also be initialized using a string constant, as follows.
char letters[ ] =”abcde”;
The string initialization automatically appends a \0 character, so the above array is of size 6, not 5. It is equivalent to writing,
char letters[ ] ={ ‘a’, b’, ‘c, d’, ‘e’, ‘\0’} ;
Thus, writing
char letters[5] =”abcde”; /* OK but bad style */
An important property of string constants is that they are allocated memory; they have an address and may be referred to by a char * pointer.
For constants of any other type, it is not possible to assign a pointer because these constants are not stored in memory and do not have an address.
However, it is perfectly valid for a character pointer to be assigned to a string constant.
char *str = “Hello World! \n”;
This is because a string constant has static extent memory which is allocated for the array before the program begins execution and exists until program termination and a string constant expression returns a pointer to the beginning of this array.
[Note: A string constant is a constant array; the memory of the array is read-only. The result of attempting to change the value of an element of a string constant is undefined.]
Example:
char *str =”This is a string constant”;
Reading and Writing String
The “%s” control string can be used in scanf() statement to read a string from the terminal and the same may be used to write a string to the terminal in printf() statement.
Example
char name[10];
scanf("%s", name);
printf("%s", name);
[Note: There is no address (&) operator used in scanf() statement.]
Example program
Program to illustrate string function.
/* program to illustrate string function */
#include <stdio.h>
#include <conio.h>
int main()
{
char ch;
int cnt = 0;
char s1[8] = "Program";
char s2[8] = {'P', 'r', 'o', 'g', 'r', 'a', 'm'};
printf("%s \n", s1);
printf("%s \n", s2);
while((ch = getchar()!='\0')&&(cnt<6-1))
s1[cnt++] = ch;
s1[cnt] = '\0';
getch();
} /* main */
Output
Program
Program
Explanation: This program aims at the concept of strings. Here the string is assigned to different arrays in different ways and the contents of these arrays can be printed using a while loop.
C language supports a wide range of string handling functions, that can be used to carry out various string manipulations.
Character operations in Strings (C language)
Character variables and constants are frequently used in relational and arithmetic expressions.
To properly use characters in such situations, it is necessary for you to understand how they are handled by the C compiler.
Whenever a character constant or variable is used in an expression in C, it is automatically converted to, and subsequently treated as an integer value.
Example;
c>= ‘a’ && c<= ‘z’
could be used to determine if the character variable ‘c’ contained a lowercase letter. As mentioned there, such an expression could be used on systems that used an ASCII character representation because the lowercase letters are represented sequentially in ASCII, with no other characters in between.
The first part of the preceding expression, which compares the value of ‘c‘ against the value of the character constant ‘a‘, is actually comparing the value of ‘c‘ against the internal representation of the character ‘a’. In ASCII, the character ‘a‘ has the value 97, the character ‘b‘ has the value 98, and so on.
Therefore, the expression c >= ‘a‘ is TRUE (nonzero) for any lowercase character contained in ‘c‘ because it has a value that is greater than or equal to 97.
However, because there are characters other than the lowercase letters whose ASCII values are greater than 97, the test must be bounded on the other end to ensure that the result of the expression is TRUE for lowercase characters only.
For this reason, ‘c‘ is compared against the character ‘z‘, which, in ASCII, has the value 122. Because comparing the value of ‘c‘ against the characters ‘a‘ and ‘z‘ in the preceding expression actually compares ‘c‘ to the numerical representations of ‘a‘ and ‘z‘.
Example program
Program to find whether the string is palindrome or not.
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main()
{
int num, i, j, result, index;
/* declaring array of string */
char name[25][25];
char temp[25];
printf("Number of names to be sorted in ascending order\n");
scanf("%d", &num);
printf("Enter %d names to be sorted\n", num);
for(i=0;i<num;i++)
/* input the names */
scanf("%s", name[i]);
for(i=0;i<num;i++)
{
index = i;
for(j=i+1;j<num;j++)
{
result = strcmp(name[index], name[j]);
if(result>0)
index = j;
}
strcpy(temp, name[index]);
strcpy(name[index], name[i]);
strcpy(name[i], temp);
}
printf("\nNames Sorted in Ascending Order\n");
for(i=0;i<num;i++)
printf("\t%s", name[i]);
}
Output:
Number of names to be sorted in ascending order : 4
Enter 4 names to be stored
Bravo
Dev
Amy
Camila
Names sorted in Ascending order
Amy
Bravo
Camila
Dev
Explanation: The main logic To sort numbers in ascending order remains the same over here, however, the only difference is that we have to use string functions to compare two strings, and also for swapping two strings we have to use string functions.
String standard functions in C language
The C Compiler Provides the following string handling functions.
Function | Purpose |
---|---|
strlen() | Used to find the length of the strings. |
strcpy() | Used to copy one string to another. |
strcat() | Used to combine two strings. |
strcmp() | Used to compare characters of two strings (difference between small and capital letters). |
strlwr() | Used to convert strings into lower case |
strupr() | Used to convert strings into upper case |
strdup() | Used to duplicate a string. |
strrev() | Used to reverse a string. |
strncpy() | Used to copy first ‘n’ characters of one string into another. |
strncmp() | Used to compare the first ‘n’ character of two strings. |
strcmpi() | Used to compare two strings without regarding the case. |
strnicmp() | Used to compare first ‘n’ characters two strings without regarding the case. |
stricmp() | Compares two strings (Not the difference between small and capital letters). |
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 the first occurrence of a given string in another string. |
strncat() | Appends source string to destination string up to the specified length. |
strnset() | Sets a specified number of characters of 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. |
The commonly used string manipulations functions are as follows
The strlen() function
This function is used to count and return the number of characters present in a string.
Syntax: var = strlen(string);
Description:
var = Is the integer variable, which accepts the length of the string.
string = Is the string constant or string variable, In which the length is going to be found. The counting ends with the first null(\0) char.
Example program
Program using strlen() function.
/* Program using strlen() function */
#include <stdio.h>
#include <conio.h>
void main()
{
char name[] = "LANG";
int len1, len2;
/* To find the length of the string */
len1 = strlen(name);
len2 = strlen("MST");
printf("\n string length of %s is %d", name, len1);
printf("\n string length of %s is %d,","MST", len2);
} /* main */
Output:
string length of LANG is 4
string length of MST is 3
Explanation: The above program refers to checking the length of the string. Here the character type name[ ] holds the elements ‘LANG‘, it passed to variable len1. The len2 variable holds the elements of ‘MST’ ‘strlen’ function to detect the length of string len1 and len2 and print the result as above mentioned.
Here, while calculating the length of the string by using the string() the ‘\0‘ null character is not taken into consideration.
The strcpy() function in c language
This function is used to copy the contents of one string to another and it almost works like a string assignment operator.
Syntax: strcpy(string1, string2);
Description:
string1 = is the destination string
string2 = is the source string
The contents of string2 are assigned to the contents of string1. Where string2 may be a character array variable or string constant.
Example:
char str1[] = "LANG";
char str2[] = "MST";
strcpy(str1, str2);
Where the contents of str2 are copied into the str1 and the contents of str1 are replaced with a new one.
Example:
char str[10];
strcpy(str1, "MST");
Here, the string constants are copied to the string variable str1.
Example program
Program using strcpy() function.
/* Program using strcpy() function */
#include <stdio.h>
void main()
{
char source = "LANG";
char target[10];
strcpy(target, source); /* string copy */
printf("\n Source string is %s", source);
printf("\n Target string is %s", target);
} /* main */
Output:
Source string is LANG
Target string is LANG
Explanation: In the program, the character type variable source contains a string “LANG”. The variable target[ ] is declared as a character type. Here the strcpy() function copy the source string “LANG” into the target string. Now the variable target also contains the string “LANG” and prints the variable source and target.
The strcat() function
The strcat() function is to concatenate or combine, two strings together and form a new concatenated string.
Syntax: strcat(string1, string2)
Description:
string1 and string2 are character-type arrays or string constants.
When the above strcat() function is executed, string2 is combined with string1 and it removes the null character (\0) of string1 and places string2 from there.
Example:
strcat(“LANG”,”MST”)
Yields LANGMST
char str1 = “LANG”
char str2 = “MST”
strcat(str1, str2)
Yields LANGMST
Example program
Program using strcat() function
/* Program using strcat() function */
#include <stdio.h>
void main()
{
/* Local definitions */
char source[] = "Program";
char target[10] = "Learn";
/* Statement */
/* string cancotenate function */
strcat(source, target);
printf("\nSource string is %s", source);
printf("\nTarget string is %s", target);
} /* main */
Output:
Source string is ProgramLearn
Target string is Learn
Explanation: In the program source[ ] is a character variable that holds the data “Program” similarly target[ ] is a character variable that holds the data “Learn”. The strcat() combines both strings and stores in the variable “source” and finally prints the variable “source” and “target” as mentioned above.
The strcmp() in function in C language
This is a function that compares two strings to find out whether they are the same or different. The two strings are compared character by character until the end of the string is reached.
If the two strings are identical, strcmp() returns a value of zero. If they are not equal, it returns the numeric difference between the first non-matching characters.
Syntax: strcmp(string1, string2);
Description:
string1 and sting2 are character-type arrays or string constants.
Example program
Program using strcmp() function.
/* Program using strcmp() function */
#include <stdio.h>
#include <conio.h>
void main()
{
/* Local definitions */
char name[] = "Tech";
char name1[] = "Guy";
int i, j, k;
/* Statement */
/* string compare function */
i = strcmp(name, "Tech");
j = strcmp(name1, name);
k = strcmp(name,"Tech Guy");
printf("\n %d %d %d", i, j, k);
} /* main */
Output:
0 -13 -32
Explanation: In the first strcmp(,) the two strings are the same, so it returns zero value. In the second, the first character of the two strings is unmatched. So the difference between ASCII values is printed.
In the third one, the strings are unmatched. The blank space is unmatched by the ‘\0’ character. So the ASCII value difference between ‘\0′ and ‘space’ is printed.
The strrev() function
The strrev() function is used to reverse a string. This function takes only one argument and returns one argument. The general form of strrev() function is
Syntax: strrev(string);
Description:
strings are character-type arrays or string constants.
Example program
Program using strrev() function.
/* Program using strrev() function */
#include <stdio.h>
void main()
{
/* Local definition */
char y[30];
printf("Enter the string :");
gets(y);
printf("The string reversed is : %s", strrev());
} /* main */
Output:
Enter the string
:
book
The string reversed is : koob
Explanation: The function strrev() is used to print the string in reverse order. The program gets the input book then reverses that string as koob and prints the result as output.
The srlwr() function
The strlwr() function converts all the uppercase characters in that string to lowercase characters.
The resultant from strlwr() is stored in the same string.
Syntax : srtlwr(string_name);
Description:
Where string_name is a string
Example program
Program using strlwr() function.
#include <stdio.h>
#include <conio.h>
int main()
{
char str[] = "LOWER CASE";
puts(strlwr(str1)); // converts to lowercase and displays it.
return 0;
}
Output:
lower case
The strchr() function
The strchr() function returns a pointer to the first occurrence of the low-order byte of ch in the string pointed to by str. If no match is found, a null pointer is returned.
Syntax: char *strchr(const char *str, int ch);
Description:
Where char is a string, ch is a character.
Example program
The program prints the string as a test.
#include<stdio.h>
#include<string.h>
int main()
{
char *p,c = 'g';
p = strchr("C Language", ' ');
printf(p);
printf("%d", c);
return 0;
}
Output
C Language
5
The strupr() function
The strupr() function converts all the lowercase characters in that string to uppercase characters. The resultant from strupr() is stored in the same string.
Syntax: strlwr(string_name);
Description:
Where string_name is a string.
Example program
Program using strupr() function.
#include<stdio.h>
#include<string.h>
int main()
{
char str1[] = "upper case";
puts(strupr(str1);
return 0;
}
Output:
UPPER CASE