You are on page 1of 18

C - Strings

Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus
a null-terminated string contains the characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To
hold the null character at the end of the array, the size of the character array containing the string
is one more than the number of characters in the word "Hello."

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization then you can write the above statement as follows −
char greeting[] = "Hello";

Following is the memory presentation of the above defined string in C/C++ −

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 define the
length of the string, i.e the number of characters strings will store. Please keep in mind that there
is an extra terminating character which is the Null character (‘\0’) used to indicate termination of
string which differs strings from normal character arrays.
Initializing a String: A string can be initialized in different ways.

There are two ways to declare a string in c language.

1. By char array
2. By string literal

We will explain this with the help of an example. Below is an example to declare a string with
name as str and initialize it with “HelloWorld”.

1.char str [] = “HelloWorld”;

2.char str[50] = “HelloWorld”;

3.char str[] = {‘H’,‘e’,‘l’,‘l’,‘o’,‘W’,‘o’,‘r’,‘l’,‘d’,‘\0’};

4.char str[11] = {‘H’,‘e’,‘l’,‘l’,‘o’,‘W’,‘o’,‘r’,‘l’,‘d’,‘\0’};

Let us now look at a sample program to get a clear understanding of declaring and initializing a
string in C and also how to print a string.
// C program to illustrate strings

#include<stdio.h>

int main()
{
// declare and initialize string
char str[] = "HelloWorld";

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

return 0;
}

Output:
Hello World
We can see in the above program that strings can be printed using a normal printf statements just
like we print any other variable. Unlike arrays we do not need to print a string, character by
character. The C language does not provide an inbuilt data type for strings but it has an access
specifier “%s” which can be used to directly print and read strings.
String I/O in C programming
String I/O:

1. printf and scanf


2. puts and gets

Syntax:
1. printf(“%s” , str)
scanf(“%s”, &str)

2. puts(str)
gets(str) [%s not required]

Read & write Strings in C using Printf() and Scanf() functions


#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];

printf("Enter your Nick name:");

/* I am reading the input string and storing it in nickname


* Array name alone works as a base address of array so
* we can use nickname instead of &nickname here
*/
scanf("%s", nickname);

/*Displaying String*/
printf("%s",nickname);

return 0;
}
Output:

Enter your Nick name:Negan


Negan
Note: %s format specifier is used for strings input/output
Read & Write Strings in C using gets() and puts() functions
#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];

/* Console display using puts */


puts("Enter your Nick name:");

/*Input using gets*/


gets(nickname);

puts(nickname);

return 0;
}

Below is a sample program to read a string from user:

// C program to read strings


#include<stdio.h>
int main()
{
// declaring string
char str[50];

// reading string
scanf("%s",str);

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

return 0;
}

You can see in the above program that string can also be read using a single scanf statement.
Also you might be thinking that why we have not used the ‘&’ sign with 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.
Passing strings to function: As strings are character arrays, so we can pass strings to function in
a same way we pass an array to a function. Below is a sample program to do this:

// C program to illustrate how to


// pass string to functions
#include<stdio.h>

void printStr(char str[])


{
printf("String is : %s",str);
}

int main()
{
// declare and initialize string
char str[] = "HelloFromBangladesh";

// print string by passing string


// to a different function
printStr(str);

return 0;
}

Output:
HelloFormBangladesh
C – String functions
Sr. Function Syntax Purpose
No.
1. strlen strlen(s1) Returns the length of string s1.
2. strlwr strlwr(s1) Converts string s1 to lowercase.
3. strupr strupr(s1) Converts string s1 to uppercase.
4. strcat strcat(s1,s2) Appends one string s2 at the end of another s1.
5. strncat strncat(s1,s2,n) Appends first n characters of string s2 at the end of s1.
6. strcpy strcpy(s1,s2) Copies a string s2 to another string s1.
7. strncpy strncpy(s1,s2,n) Copies first n characters of string s2 at the end of s1.
8. strcmp strcmp(s1,s2) Compares two strings.
9. strncmp strncmp(s1,s2,n) Compares first n characters of two string.
10. strcmpi strcmpi(s1,s2) Compares two strings regardless of case.
11. strncmpi strncmpi(s1,s2,n) Compares first n characters of two strings regardless
of case. Not case sensitive.
12. strdup s2= strdup(s1) Duplicates a string.
13. strchr strchr(s1,ch) Finds out first occurrence of a given character (ch) in
a string (s1).
14. strrchr strrchr(s1,ch) Finds out last occurrence of a given character (ch) in a
string (s1).
15. strset strset(s1,ch) Sets all characters of string (s1) to a given character
(ch).
16. strnset strnset(s1,ch,n) Sets first n characters of string (s1) to a given
character (ch).
17. strrev s2=strrev(s1) Reverves a string.
C String function – strlen
Syntax:

size_t strlen(const char *str)


size_t represents unsigned short
It returns the length of the string without including end character (terminating
char ‘\0’).

Example of strlen:

#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "MPE,AUST";
printf("Length of string str1: %d", strlen(str1));
return 0;
}
Output:

Length of string str1: 8


strlen vs sizeof
strlen returns you the length of the string stored in array, however sizeof returns
the total allocated size assigned to the array. So if I consider the above example
again then the following statements would return the below values.

returned value 8.
strlen(str1)
would return value 20 as the array size is 20 (see the first statement in
sizeof(str1)
main function).

C String function – strnlen


Syntax:

size_t strnlen(const char *str, size_t maxlen)

size_t represents unsigned short


It returns length of the string if it is less than the value specified for maxlen
(maximum length) otherwise it returns maxlen value.
Example of strnlen:

#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "String Functions";
printf("Length of string str1 when maxlen is 30: %d", strnlen(str1, 30));
printf("Length of string str1 when maxlen is 10: %d", strnlen(str1, 10));
return 0;
}
Output:
Length of string str1 when maxlen is 30: 13
Length of string str1 when maxlen is 10: 10

Have you noticed the output of second printf statement, even though the string
length was 13 it returned only 10 because the maxlen was 10.

C String function – strcmp


int strcmp(const char *str1, const char *str2)
It compares the two strings and returns an integer value. If both the strings are
same (equal) then this function would return 0 otherwise it may return a negative
or positive value based on the comparison.

If string1 < string2 OR string1 is a substring of string2 then it would result in


a negative value. If string1 > string2 then it would return positive value.
If string1 == string2 then you would get 0(zero) when you use this function for
compare strings.

Example of strcmp:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "String Function";
char s2[20] = "String Functions Uses";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:

string 1 and 2 are different

C String function – strncmp


int strncmp(const char *str1, const char *str2, size_t n)
size_t is for unassigned short
It compares both the string till n characters or in other words it compares first n
characters of both the strings.

Example of strncmp:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "String Function ";
char s2[20] = "String Function Uses” ;
/* below it is comparing first 8 characters of s1 and s2*/
if (strncmp(s1, s2, 8) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:

string1 and string 2 are equal

C String function – strcat


char *strcat(char *str1, char *str2)
It concatenates two strings and returns the concatenated string.

Example of strcat:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}
Output:

Output string after concatenation: HelloWorld

C String function – strncat


char *strncat(char *str1, char *str2, int n)
It concatenates n characters of str2 to string str1. A terminator char (‘\0’) will
always be appended at the end of the concatenated string.

Example of strncat:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
printf("Concatenation using strncat: %s", s1);
return 0;
}
Output:

Concatenation using strncat: HelloWor


C String function – strcpy
char *strcpy( char *str1, char *str2)
It copies the string str2 into string str1, including the end character (terminator
char ‘\0’).

Example of strcpy:

#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[40] = "string 2 : I’m gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}
Output:

String s1 is: string 2: I’m gonna copied into s1

C String function – strncpy


char *strncpy( char *str1, char *str2, size_t n)
size_t is unassigned short and n is a number.
Case1: If length of str2 > n then it just copies first n characters of str2 into str1.
Case2: If length of str2 < n then it copies all the characters of str2 into str1 and
appends several terminator chars(‘\0’) to accumulate the length of str1 to make it
n.

Example of strncpy:

#include <stdio.h>
#include <string.h>
int main()
{
char first[30] = "string 1";
char second[30] = "string 2: I’m using strncpy now";
/* this function has copied first 10 chars of s2 into s1*/
strncpy(s1,s2, 12);
printf("String s1 is: %s", s1);
return 0;
}
Output:

String s1 is: string 2: I’m

C String function – strchr


char *strchr(char *str, int ch)
It searches string str for character ch (you may be wondering that in above
definition I have given data type of ch as int, don’t worry I didn’t make any
mistake it should be int only. The thing is when we give any character while using
strchr then it internally gets converted into integer for better searching.

Example of strchr:

#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "I’m an example of function strchr";
printf ("%s", strchr(mystr, 'f'));
return 0;
}
Output:

f function strchr

C String function – Strrchr


char *strrchr(char *str, int ch)
It is similar to the function strchr, the only difference is that it searches the string
in reverse order, now you would have understood why we have extra r in strrchr,
yes you guessed it correct, it is for reverse only.

Now let’s take the same above example:

#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "I’m an example of function strchr";
printf ("%s", strrchr(mystr, 'f'));
return 0;
}
Output:

function strchr
Why output is different than strchr? It is because it started searching from the
end of the string and found the first ‘f’ in function instead of ‘of’.

C String function – strrev


char *strrev(char *str);
It reveres a string.

Example of strrev:

#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "MPE,AUST";
printf("The reverse string of string str1: %s", strlen(str1));
return 0;
}
Output:

The reverse string of string str1: TUSA,EPM


C Program – finding length of a String without using
standard library function strlen
/**
* C program to find length of a string using for loop
*/

#include <stdio.h>
#define MAX_SIZE 100 // Maximum size of the string

int main()
{
char text[MAX_SIZE]; /* Declares a string of size 100 */
int i;
int count= 0;

/* Input a string from user */


printf("Enter any string: ");
gets(text);

/* Iterate till the last character of string */


for(i=0; text[i]!='\0'; i++)
{
count++;
}

printf("Length of '%s' = %d", text, count);

return 0;
}
C Program –Copy a String without using standard
library function strcpy
/**
* C program to copy one string to another string without using strcpy()
*/

#include <stdio.h>
#define MAX_SIZE 100 // Maximum size of the string

int main()
{
char text1[MAX_SIZE];
char text2[MAX_SIZE];
int i;

/* Input string from user */


printf("Enter any string: ");
gets(text1);

/* Copy text1 to text2 character by character */


for(i=0; text1[i]!='\0'; i++)
{
text2[i] = text1[i];
}

//Makes sure that the string is NULL terminated


text2[i] = '\0';

printf("First string = %s\n", text1);


printf("Second string = %s\n", text2);
printf("Total characters copied = %d\n", i);

return 0;
}

C Program – concat a String without using standard


library function strcat
/**
* C program to concatenate two strings
*/

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
int main()
{
char str1[MAX_SIZE], str2[MAX_SIZE];
int i, j;

/* Input two strings from user */


printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);

/* Move till the end of str1 */


i=0;
while(str1[i] != '\0')
{
i++;
}

/* Copy str2 to str1 */


j = 0;
while(str2[j] != '\0')
{
str1[i] = str2[j];
i++;
j++;
}

// Make sure that str1 is NULL terminated


str1[i] = '\0';

printf("Concatenated string = %s", str1);

return 0;
}

C Program – convert a String to uppercase without


using standard library function strupr
/**
* C program to convert string to uppercase
*/

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size

int main()
{
char str[MAX_SIZE];
int i;

/* Input string from user */


printf("Enter your text : ");
gets(str);

for(i=0; str[i]!='\0'; i++)


{
/*
* If current character is lowercase alphabet then
* convert it to uppercase.
*/
if(str[i]>='a' && str[i]<='z')
{
str[i] = str[i] - 32;
}
}

printf("Uppercase string : %s",str);


return 0;
}

Write a C program to search all occurrences of a


character in given string.
#include <stdio.h>

#define MAX_SIZE 100 // Maximum string size

int main()

char str[MAX_SIZE];

char toSearch;

int i;

/* Input string and character to search from user */

printf("Enter any string: ");

gets(str);

printf("Enter any character to search: ");


toSearch = getchar();

/* Run loop till the last character of string */

i=0;

while(str[i]!='\0')

/* If character is found in string */

if(str[i] == toSearch)

printf("'%c' is found at index %d\n", toSearch, i);

i++;

return 0;

You might also like