You are on page 1of 12

UNIT 4 (Strings in C)

String in C programming is a sequence of characters terminated with a null character ‘\0’.


Strings are defined as an array of characters. The difference between a character array and a
string is the string is terminated with a unique character ‘\0’.
Example of C String:

Declaration of Strings
Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax
for declaring a string.
char str_name[size];
In the above syntax str_name is any name given to the string variable and size is used to define
the length of the string, i.e the number of characters strings will store.

Note: There is an extra terminating character which is the Null character (‘\0’) used to
indicate the termination of a string that differs strings from normal character arrays.

When a Sequence of characters enclosed in the double quotation marks is encountered by the
compiler, a null character ‘\0’ is appended at the end of the string by default.

Initializing a String
A string can be initialized in different ways. We will explain this with the help of an example.
Below are the examples to declare a string with the name str and initialize it with
“GeeksforGeeks”.

4 Ways to Initialize a String in C

1. Assigning a string literal without size: String literals can be assigned without size.
Here, the name of the string str acts as a pointer because it is an array.
char str[] = "GeeksforGeeks";
2. Assigning a string literal with a predefined size: String literals can be assigned with
a predefined size. But we should always account for one extra space which will be
assigned to the null character. If we want to store a string of size n then we should
always declare a string with a size equal to or greater than n+1.
char str[50] = "GeeksforGeeks";
3. Assigning character by character with size: We can also assign a string character by
character. But we should remember to set the end character as ‘\0’ which is a null
character.
char str[14] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
4. Assigning character by character without size: We can assign character by character
without size with the NULL character at the end. The size of the string is determined
by the compiler automatically.
char str[] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
Below is the memory representation of the string “Geeks”.

Let us now look at a sample program to get a clear understanding of declaring, initializing a
string in C, and also how to print a string with its size.

// C program to illustrate strings


#include <stdio.h>
#include <string.h>
int main()
{
// declare and initialize string
char str[] = "Geeks";

// print string
printf("%s\n", str);

int length = 0;
length = strlen(str);

// displaying the length of string


printf("Length of string str is %d", length);

return 0;
}

Output
Geeks
Length of string str is 5

We can see in the above program that strings can be printed using normal printf statements just
like we print any other variable. Unlike arrays, we do not need to print a string, character by
character.

Note: The C language does not provide an inbuilt data type for strings but it has an access
specifier “%s” which can be used to print and read strings directly.

How to Read a String From User?

// C program to read string from user


#include<stdio.h>
int main()
{
char str[50]; // declaring string
scanf("%s",str); // reading string
printf("%s",str); // print string
return 0;
}
Input:
GeeksforGeeks

Output:
GeeksforGeeks

You can see in the above program that the string can also be read using a single scanf
statement. Also, you might be thinking that why we have not used the ‘&’ sign with the string
name ‘str’ in scanf statement! To understand this you will have to recall your knowledge of
scanf.
We know that the ‘&’ sign is used to provide the address of the variable to the scanf()
function to store the value read in memory. As str[] is a character array so using str without
braces ‘[‘ and ‘]’ will give the base address of this string. That’s why we have not used ‘&’ in
this case as we are already providing the base address of the string to scanf.

How to read a line of text?

The scanf() operation cannot read strings with spaces as it automatically stops reading when it
encounters whitespace. To read and print strings with whitespace, we can use the combination
of fgets() and puts():

fgets() The fgets() function is used to read a specified number of characters. Its declaration
looks as follows:

fgets(name_of_string, number_of_characters, stdin);


name_of_string: It is the variable in which the string is going to be
stored. number_of_characters: The maximum length of the string should be read. stdin: It is
the filehandle from where the string is to be read.

puts() puts() is very convenient for displaying strings.


puts(name_of_string);
name_of_string: It is the variable in which the string will be stored.

An example using both functions:


#include <stdlib.h>
#include <stdio.h>
int main() {
char str[30];
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
printf("The string is: ");
puts(str);
return 0;
}

Input:
Enter string: Scaler is amazing.

Output:
The string is: Scaler is amazing.

In the above example, we can see that the entire string with the whitespace was stored and
displayed, thus showing us the power of fgets() and puts().
Highlights: The combination of fgets() and puts() is used to tackle the problem of reading a
line of text with whitespace.

Passing strings to functions

As strings are simply character arrays, we can pass strings to function in the same way we pass
an array to a function, either as an array or as a pointer. Let's understand this with the following
program:

#include <stdio.h>
void pointer(char * str) {
printf("The string is : ");
puts(str);
printf("\n");
}
void array(char str[]) {
printf("The string is : ");
puts(str);
printf("\n");
}
int main() {
char str[25] = "Scaler is amazing.";
pointer(str);
array(str);
return 0;
}

Output:
The string is : Scaler is amazing.
The string is : Scaler is amazing

String Handling Functions:

C supports a large number of string handling functions in the standard library "string.h". You
have to include the code below to run string handling functions.

#include <string.h>

Few commonly used string handling functions are discussed below:


Function Name Description

strlen(string_name) Returns the length of string name.

strcpy(s1, s2) Copies the contents of string s2 to string s1.

Compares the first string with the second string. If strings are the
strcmp(str1, str2) same it returns 0.

Concat s1 string with s2 string and the result is stored in the first
strcat(s1, s2) string.

strlwr() Converts string to lowercase.


Function Name Description

strupr() Converts string to uppercase.

strstr(s1, s2) Find the first occurrence of s2 in s1.

strrev(string) returns reverse string.

C String Length: strlen() function: The strlen() function returns the length of the given string.
It doesn't count null character '\0'.
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}

Output:
Length of string is: 10

C Copy String: strcpy(): The strcpy(destination, source) function copies the source string in
destination.
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
return 0;
}

Output:
Value of second string is: javatpoint

C String Concatenation: strcat(): The strcat(first_string, second_string) function


concatenates two strings and result is returned to first_string.
#include<stdio.h>
#include <string.h>
int main(){
char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[10]={'c', '\0'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
return 0;
}

Output:
Value of first string is: helloc

C Compare String: strcmp(): The strcmp(first_string, second_string) function compares two


string and returns 0 if both strings are equal.

Here, we are using gets() function which reads string from the console.
#include<stdio.h>
#include <string.h>
int main(){
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}

Output:
Enter 1st string: hello
Enter 2nd string: hello
Strings are equal

C Reverse String: strrev(): The strrev(string) function returns reverse of the given string.
Let's see a simple example of strrev() function.
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
Output:
Enter string: javatpoint
String is: javatpoint
Reverse String is: tnioptavaj

C String Lowercase: strlwr(): The strlwr(string) function returns string characters in


lowercase. Let's see a simple example of strlwr() function.

#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nLower String is: %s",strlwr(str));
return 0;
}

Output:
Enter string: JAVATpoint
String is: JAVATpoint
Lower String is: javatpoint

C String Uppercase: strupr(): The strupr(string) function returns string characters in


uppercase. Let's see a simple example of strupr() function.

#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nUpper String is: %s",strupr(str));
return 0;
}

Output:
Enter string: javatpoint
String is: javatpoint
Upper String is: JAVATPOINT

C String strstr(): The strstr() function returns pointer to the first occurrence of the matched
string in the given string. It is used to return substring from first match till the last character.
Syntax:

1. char *strstr(const char *string, const char *match)

String strstr() parameters

string: It represents the full string from where substring will be searched.

match: It represents the substring to be searched in the full string.

String strstr() example


#include<stdio.h>
#include <string.h>
int main(){
char str[100]="this is javatpoint with c and java";
char *sub;
sub=strstr(str,"java");
printf("\nSubstring is: %s",sub);
return 0;
}

Output:
javatpoint with c and java

Printing each character of a string


We save a string in a character array and we know that array elements are indexe d. So, we
can access them using their index number.

In the following example we have a variable str which holds a string "Hello" and we will
print each character in the string.

Strings ends with a NULL \0 character in C.

The trick here is to keep printing the characters as long as we don't hit the NULL character
which marks the end of a string in C. So, lets write a C program.
#include <stdio.h>
int main(void)
{
char str[] = "Hello";
int i;

i = 0;
while(str[i] != '\0') {
printf("%c\n", str[i]);
i++;
}

printf("End of code\n");
return 0;
}
Output
H
e
l
l
o
End of code

How to Find the String Length in C?


We can find the length of a String by counting all the characters in it (before the null
character) using a for loop. We can also use the built-in string.h library function strlen() or
the sizeof() operator.

#include <stdio.h>
int str_length(char str[]) // The User-defined method
{
int count; // initializing count variable (stores the length of the string)
for (count = 0; str[count] != '\0'; ++count); // incrementing the count till the end of the string
return count; // returning the character count of the string
}
int main() {
char str[1000]; // initializing the array to store string characters
printf("Enter the string: ");
scanf("%s", str);
int length = str_length(str); // assigning the count of characters in the string to the length of
the string
printf("The length of the string is %d", length); // printing the length of string
return 0;
}
OUTPUT:
Enter the string: 567lens
The length of the string is 7

// finding the length of a string using the strlen() function from the string.h library

#include <stdio.h>
#include <string.h>
int main() {
char str[1000];
printf("Enter the string: ");
scanf("%s", str);
int length;
length = strlen(str);
printf("The length of the string is %d", length);
return 0;
}
OUTPUT:
Enter the string: 567lens

C program to print all VOWEL and CONSONANT characters separately.

In this program we will print all VOWEL and CONSONANT characters from entered
string separately, logic behind to implement this program too easy, you have to just check if
characters are vowels print them as vowels and not print them as consonants.

/*C program to count upper case, lower case and special characters in a string.*/
#include<stdio.h>
int main()
{
char text[100];
int i;
int countL,countU,countS;

printf("Enter any string: ");


gets(text);

//here, we are printing string using printf without using loop


printf("Entered string is: %s\n",text);

//count lower case, upper case and special characters assign 0 to counter variables
countL=countU=countS=0;

for(i=0;text[i]!='\0';i++)
{
//check for alphabet
if((text[i]>='A' && text[i]<='Z') || (text[i]>='a' && text[i]<='z'))
{
if((text[i]>='A' && text[i]<='Z'))
{
//it is upper case alphabet
countU++;
}
else
{
//it is lower case character
countL++;
}
}
else
{
//character is not an alphabet
countS++; //it is special character
}
}
printf("Upper case characters: %d\n",countU);
printf("Lower case characters: %d\n",countL);
printf("Special characters: %d\n",countS);
return 0;
}

OUTPUT:
Enter any string: www.includehelp.com
String is: www.includehelp.com
VOWEL Characters are: iueeo
CONSONANT Characters are: www.ncldhlp.cm

C program to convert string in upper case and lower case.


In this program, we will convert string in upper case and lower case. First we will read a
string and then convert string in upper case and after printing the string that is converted into
upper case, we will convert it in lower case and print the lower case. Logic behind to implement
this program - Just check the alphabets if they are in upper case add the value 32 [0x20 - hex
value] to convert the character into lower case otherwise subtract 32 [0x20 - hex value] to
convert the character into upper case.

Because difference between in the ascii codes of upper case and lowe r case characters are 32
[0x20 - hex value].

/*C program to convert string in upper case and lower case.*/


#include<stdio.h>
int main()
{
char text[100];
int i;
printf("Enter any string: ");
gets(text);
printf("Entered string is: %s\n",text);

//convert into upper case


for(i=0;text[i]!='\0';i++)
{
if(text[i]>='a' && text[i]<='z')
text[i]=text[i]-0x20;
}
printf("String in Upper case is: %s\n",text);

//convert into lower case


for(i=0;text[i]!='\0';i++)
{
if(text[i]>='A' && text[i]<='Z')
text[i]=text[i]+0x20;
}
printf("String in Lower case is: %s\n",text);

return 0;
}
Enter any string: www.IncludeHelp.com
Entered string is: www.IncludeHelp.com
String in Upper case is: WWW.INCLUDEHELP.COM
String in Lower case is: www.includehelp.com

You might also like