Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconTop 7 Popular String Functions in C [With Examples]

Top 7 Popular String Functions in C [With Examples]

Last updated:
25th Jul, 2022
Views
Read Time
13 Mins
share image icon
In this article
Chevron in toc
View All
Top 7 Popular String Functions in C [With Examples]

Summary:

In this article, you will learn about Popular String functions in C. Take a look below.

  1.  puts() and gets()
  2. strcat()
  3. Function strlen()
  4. Function strcpy()
  5. Function strcmp()
  6. Functions strlwr() / strupr()
  7. Function strrev()

Read the full article to know more.

Strings in C language are an array of characters ended with null characters (‘\0’). The null character at the end of a string indicates its end and the strings are always enclosed by double quotes. In C language characters are enclosed by single quotes. Some examples of both of them are shown below.

Also, check out our free courses to get an edge over the competition.

Ads of upGrad blog

String functions are usually used to manipulate the strings.

Example or Representation of C Characters and Strings

  • char string[10] = { ‘s’,’d’,’f’,’d’,’t’,’j’,’a’,’\0’ };
  • char string[10]=” fresher”;
  • char string[]=” fresher”;

There is a minor difference between the declarations of the strings in both of the above statements. Like when we declare char as string[10], 10 bytes of memory space gets allocated to hold the 10 values of string, while when we declare it like string[] then memory gets allocated at the time of execution of the program.

To find the length of any string, manual programming can be done but it could be a time-consuming task, rather one can use the string functions directly to save time and effort.

Explore Our Software Development Free Courses

String Declaration and Initialization

In C programming, the strings can be declared in two ways as shown above. In C programming, a string is a sequence of characters that are terminated with a null or ‘\0’ character. An example of the same is given below:

char temp[]=” temp string”;

You can also consider doing our Java Bootcamp course from upGrad to upskill your career.

When a string of character is declared of char type that is enclosed in a double quotation mark, then \0 is automatically appended at the end of the string. For example –

char temp[]=” temp string”;

temp string\0

String Declaration

A string in language C is declared in the following manner:

char temp[5];

     

  s[0]      s[1]      s[2]      s[3]      s[4]

In this way, we can initialize a string of length 5.

To declare a string in C, a data array should be used because C does not support string as a data type. While declaring a C string, the size of a variable must be defined for it to calculate the number of characters going to be stored inside the string variable in C.

Featured Program for you: Fullstack Development Bootcamp Course

String Initialization

String initialization can be done in many ways and some of them are given below:

 char t[]=” temp string”;

char t[10]=” temp string”;

char t[]={‘t’,’e’,’m’, ‘d’,’\0’};

char t[5]={‘t’,’e’,’m’, ‘d’,’\0’};

Temp\0

t[0]       t[1]      t[2]      t[3]      t[4]

In the above type of declaration, we can only store the strings that have only four characters. While if you want to store five characters in such string or array, then you may need the character array of more length.

C language allows initialisation of string variables without defining the string array. It can be done in the following way –

char color_name [ ] = “BLUE”;

Explore our Popular Software Engineering Courses

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

 

Assigning Values to Strings

Arrays and strings do not support the assignment operators. Once the strings are declared you cannot assign the values to string-type variables. For example in C language we cannot write and assign the values in the following way:

char t[100];

t=” temp value”;

Strings are copied by value, not reference. String assignment happens using the =operator followed by the copied actual bytes from the operand up source. The new type string variable can be created by assigning it an expression of the type string.

Learn Software Engineering Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

String Handling in C

Now we are going to enlist some of the popular string functions in C that make string handling quite easier. Multiple operations on the string like reading the String, Copying or Reversing the String and many other operations can be easily performed on the strings by using these functions.

Read: String Array In Java: Java String Array With Coding Examples

String operators or string functions can be used directly to manipulate the strings. Here, in this article we will explain the library functions like gets(), puts(), strlen(), strcopy(), and many others to explain string handling in C.

Sometimes programmers have to write the string functions to manipulate them as per the required problem. However, string manipulation can be done manually, but this can make the programming quite complex and large.

There are predefined string functions in the C language, namely string handling functions. There is a header file defined for these functions named as string.h. While string handling it is important to use a header file of string.h while doing string handling C.

In-Demand Software Development Skills

List of some Common String Handling Functions in C

FunctionDescription
strlen()Can compute the length of the string
Strcpy()Can copy the content of a string to another
Strcat()Is used to concatenate or join two strings
Strcmp()Can compare two strings
Strlwr()Can convert the string to lowercase
Strupr()Is used to convert the letters of string to uppercase
Strrev()Is used to reverse the string

When you have to use any of the string handling functions in your program, the functions are not limited only to these many. There are many other string functions as well. So, let’s discuss them:

1) puts() and gets()

The two popular functions of string header file gets and puts are used to take the input from the user and display the string respectively.To understand briefly the working of the string handling functions in c of puts and gets,  the gets() function, allows the ensure to enter characters followed by enter key. And it also enables the user to add spaced separated strings. Whereas, the puts() function is also one of the types of strings in C, is used for writing a line for the output screen. It is similar to the printf() function

Both of these functions are defined in string.h file. Let’s see one example of these functions:

#include main()

Int main()

{

char temp[20];

printf(“Enter your Name”);

gets(temp);

printf(“My Name is: ”);

puts(temp);

return 0;

}

2) strcat()

For the cases when one string has to be appended at the end of another string, this function is being used. Function strcat can append a copy of the source string at the end of the destination string. The strcat() is one of the string operations in c which concatenates two strings, meaning it joins the character strings end-to-end. In the strcat() operation, the destination string’s null character will be overwritten by the source string’s first character, and the previous null character would now be added at the end of the new destination string which is a result of stcrat() operation.

The user has to pass two arguments that are described below:

i) src

ii) dest

Here at the place of “src” string is specified, while at the place of ‘dest’ the destination string in which we have to append the source string is specified.

Example

#include<string.h>

int main()

{

char src[20]= “ before”;

char dest[20]= “after ”;

strcat(dest, src);

puts(dest);

return 0;

}

The output will be: after before

3) Function strlen()

One more function of string header file that can be directly used for the strings is strlen(). You can use the function strlen(), the string function in C, when you have to find out the length of any string. The strlen() string functions in c basically calculate the length of a given string. However, one can also write a program manually to find out the length of any string, but the use of this direct function can save your time and the example is given below:

#include<stdio.h>

int main()

{

int length;

char s[20] = “We are Here”;

length=strlen(s);

printf(“\Length of the string is = %d \n”, length);

return 0;

}

Length of the string is = 11

4) Function strcpy()

If you have to copy the content of one string to another string, then this function is being used. Even the null characters are copied in the process. Syntax of the function is strcpy(dest,source). The function can copy the content of one string to another. One example of the function is given below:

#include<string.h>

int main()

{

char src[20]= “ Destination”;

char dest[20]= “”;

printf(“\n source string is = %s”, src);

printf(“\n destination string is = %s”, dest);

strcpy(dest, src);

printf (“\ntarget string after strcpy() = %s”, dest);

return 0;

}

Output

Source string is = Destination

Target string is =

Target string after strcpy() = Destination

Learn: StringBuffer vs. StringBuilder: Difference Between StringBuffer & StringBuilder

5) Function strcmp()

To compare two strings to know whether they are same or not we can use strcmp() function.This string functions in c, compares two strings. While comparing the strings takes two parameters into account namely –

  1. str1
  2. str2

On comparing the return value be determined basis the strings setup as shown below.

The function returns a definite value that may be either 0,  >0, or <0. In this function, the two values passed are treated as case sensitive means ‘A’ and ‘a’ are treated as different letters. The values returned by the function are used as:

i) 0 is returned when two strings are the same

ii) If str1<str2 then a negative value is returned

iii) If str1>str2 then a positive value is returned

Example:

#include<stdio.h>

#include<string.h>

int main()

{

char str1[]=”copy”;

char str2[]=”Trophy”;

int I,j,k;

i=strcmp(str1, “copy”);

j=strcmp(str1, str2);

k-strcmp(str1, “f”);

printf(“\n %d %d %d”,I,j,k);

return 0;

}

Output: 0  -1  1

6) Functions strlwr() / strupr()

Sometimes you may need to convert the lowercase letters of any string to the uppercase or vice-versa.  As it can be understood the lwr stands for lowercase and upr stands for uppercase. For this purpose there are two direct string functions in C, they can be used to perform the conversions either from upper to lower case or vice-versa. Here, we have explained an example of the same:

#include<stdio.h>

#include<string.h>

int main()

{

char str[]=”CONVERT me To the Lower Case”;

printf(“%s\n”, strlwr(str));

return 0;

}

Output: convert me to the lower case

Similarly, if we will use the strupr function in place of strlwr, then all the content will be converted to the upper case letters. We can use the strupr function, defined in the string header file. Through this function, all letters of the string are converted, that too without any long manual procedure.

Also visit upGrad’s Degree Counselling page for all undergraduate and postgraduate programs.

7) Function strrev()

If you want to reverse any string without writing any huge or extensive program manually, then you can use this function. The rev in the strrev() stands for reverse and it is used to reverse the given string. Function strrev() is used to reverse the content of the string. Strrev function is used to check the nature of the string, whether the given string is a palindrome or not. Several other uses and applications are also present in the string reverse function. One of its uses is given below:

#include<stdio.h>

#include<string.h>

int main()

{

char temp[20]=”Reverse”;

printf(“String before reversing is : %s\n”, temp);

printf(“String after strrev() :%s”, strrev(temp));

return 0;

}

Also Read: Scanner Class in Java: Types of Constructors & Methods, How to Use

Some more String Handling Functions with Purpose:

Ads of upGrad blog

As we said earlier that there exist more string functions in C. Some other commonly used functions for string handling in C are:

FunctionPurpose
strchr()It returns a pointer to the  first occurrence of char in str1
strdup()It can duplicate the string
strset()Sets all characters of a string to the given character
strrchr()Used to locate the occurrence of a first pointing character
——-———————————

Read our Popular Articles related to Software Development

Final Words

Just like every other language C, also has a vast library of ready-to-use or in-built functions. To handle any string of characters, you can use these functions directly. However, the functions are not limited to these ones. There are many other string functions in C in the header file. A major benefit of them is to cut the time and length of coding.

In this article we have discussed various string handling functions in c with examples, this has given us a good understanding of how useful these functions are as they decrease the time of getting the output. Also, these string functions in c with examples tell us how we can reduce the chances of error, as manual programming can induce errors but with these quick functions and keys, the possibility of an error reduces.

If you’re interested to learn more about Java, OOPs & full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What are the differences between C and C#?

C is a classical high-level computer language that supports procedural programming. C#, pronounced as C-Sharp, is an object-oriented programming language that was developed as a counterpart of Java. C does not conform to object-oriented principles and does not come with automatic garbage collection features. C#, on the other hand, supports garbage collection via Common Language Runtime (CLR). C programs can be executed across platforms, while C# needs the .NET platform to run. While C# is more focused on the design, C is more about the functional aspects. Both languages support pointers, but in C#, pointers can only be used in unsafe mode.

2Can you use C syntax while writing C++ programs?

Yes, you can use C syntaxes when you are writing a program in C++. But for mixing codes successfully, the primary requirement is that your C and C++ compilers must be compatible. All C++ compilers support linking to C for some C-compatible compilers. For instance, the compilers must define fundamental types like int, float, and pointer in identical ways. The C++ programming language comes with a feature called linkage specification, using which you need to declare an object or function such that it adheres to the linkage conventions for the supported language kind. By default, the linkage setting for objects and functions in C++.

3Is there still any demand for C?

Even though several decades have passed since the inception of the C programming language, it still remains one of the most salient programming languages in the IT industry. C is one of the foremost computer languages that form the fundamentals of the software industry. So it will always be in demand as the fundamental stepping stone for shaping the careers of computer programmers. Though there are highly advanced programming languages like Python and Java in the market, programmers are expected to be familiar with C. Starting from developing games and server-side applications to program architecture and embedded systems engineering, C makes it all possible.

4How are strings stored in C?

The strings are stored in a memory, and they get terminated by the null character. The strings are nothing but characters arranged sequentially. The string characters are basically sored as the array of chars which is terminated by the null byte.

5What are the features of a string?

1. It is made up of various characters arranged sequentially. 2. These characters are nothing but digits, numbers, etc. 3. A correct way to write them is to put them under quotation marks. 4. One string cannot perform all tasks, for this, there are different string functions.

6What is recursion in C?

It is a process in which a function calls itself on its own either directly or indirectly. The function which performs this operation is called a recursive function. The importance of this function is to solve the problems which can be broken into smaller and recurring problems.

7Why is string called a string?

The reason behind a string being called a string is its arrangement level, they are characters(numbers, digits, etc.) arranged in a sequential manner. This sequence looks like a string, that is why the name string is used.

8Can you scanf a string in C?

The function of sacnf is to read the string. It reads and detects the presence of whitespaces in a string. Upon reading, it encounters the whitespaces such as any space, new line, newly added tab, etc. After detection, it stops the usage of any whitespace which is not included in the format of a string.

Explore Free Courses

Suggested Tutorials

View All

Suggested Blogs

Top 7 Node js Project Ideas &#038; Topics
31544
Node.JS is a part of the famous MEAN stack used for web development purposes. An open-sourced server environment, Node is written on JavaScript and he
Read More

by Rohan Vats

05 Mar 2024

How to Rename Column Name in SQL
46899
Introduction We are surrounded by Data. We used to store information on paper in enormous file organizers. But eventually, we have come to store it o
Read More

by Rohan Vats

04 Mar 2024

Android Developer Salary in India in 2024 [For Freshers &#038; Experienced]
901297
Wondering what is the range of Android Developer Salary in India? Software engineering is one of the most sought after courses in India. It is a reno
Read More

by Rohan Vats

04 Mar 2024

7 Top Django Projects on Github [For Beginners &amp; Experienced]
51974
One of the best ways to learn a skill is to use it, and what better way to do this than to work on projects? So in this article, we’re sharing t
Read More

by Rohan Vats

04 Mar 2024

Salesforce Developer Salary in India in 2024 [For Freshers &#038; Experienced]
909113
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

04 Mar 2024

15 Must-Know Spring MVC Interview Questions
34717
Spring has become one of the most used Java frameworks for the development of web-applications. All the new Java applications are by default using Spr
Read More

by Arjun Mathur

04 Mar 2024

Front End Developer Salary in India in 2023 [For Freshers &#038; Experienced]
902366
Wondering what is the range of front end developer salary in India? Do you know what front end developers do and the salary they earn? Do you know wh
Read More

by Rohan Vats

04 Mar 2024

Method Overloading in Java [With Examples]
26122
Java is a versatile language that follows the concepts of Object-Oriented Programming. Many features of object-oriented programming make the code modu
Read More

by Rohan Vats

27 Feb 2024

50 Most Asked Javascript Interview Questions &#038; Answers [2024]
4323
Javascript Interview Question and Answers In this article, we have compiled the most frequently asked JavaScript Interview Questions. These questions
Read More

by Kechit Goyal

26 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon