Strings in C with Examples: String Functions

Strings in C with Examples: String Functions

11 Apr 2024
Intermediate
2.21K Views
15 min read
Learn via Video Course & by Doing Hands-on Labs

C Programming For Beginners Free Course

Strings in C: An Overview

Strings in C language are an arranged order of characters having a null character in the end '\0'. Strings are utilized in almost any programming language, and anyone interested in programming needs to understand them. In this C tutorial, we'll explore what strings are, how they work, and what you need to know when working with them in the C language. To get a little deeper, consider our C Programming Course.

What are Strings in C?

A string is a sequence of characters. e.g. "ScholarHat". Many programming languages like Java have a data type known as a string for storing string values. In C, a string is stored as an array of characters. You have to use char data type and make an array of characters to create a string. The string is terminated with a null character '\0'.

A string is represented using double quotes, ("") or single quotes (''). Whenever an array of characters e.g. c[10] gets created, the compiler implicitly appends '\0' at the end of the string.

strings in c programming

How to declare a string in C?

Syntax


char variableName{size];

Example


char str[20];

Here, a string, str gets created that can store 20 characters.

How to initialize a String in C?

There are two methods to do this

  1. Using char array

  • without declaring the size of the array
    
    char str[] = {'S', 'c', 'h', 'o', 'l', 'a', 'r', 'H', 'a', 't', '\0'};
    
  • by declaring the size of the array
    
    char str[10] = {'S', 'c', 'h', 'o', 'l', 'a', 'r', 'H', 'a', 't', '\0'};
    

    You might have noticed that in this method, we are manually appending '\0' at the end of every string.'\0' is necessary as it indicates the end of the string.

  1. Using string literal

  • without declaring the size of the array
    
    char str[]="ScholarHat";
    
  • by declaring the size of the array
    
    char str[10]="ScholarHat";
    

    This is the easiest method. There is no need to manually append a '\0' at the end of the string. When the compiler sees something written in "", it understands it as a string and adds '\0' at the end by default.

String Program in C Compiler

#include <stdio.h>
int main(){ 
 char str1[10]={'S', 'c', 'h', 'o', 'l', 'a', 'r', 'H', 'a', 't', '\0'}; 
 char str2[10]="ScholarHat"; 
 
 printf("String by char array method: %s\n", str1); 
 printf("String by String Literal method: %s\n", str2); 
 return 0; 
} 

Here, we are printing the string, "Scholarhat" using both the methods discussed above

Note: %s is the format specifier to print a string in C.

Output

String by char array method: ScholarHat
String by String Literal method: ScholarHat

Read More - Top 50 Mostly Asked C Interview Questions

How to access a String in C?

As the string isarray of characters, we can access the characters of the string with their index number. The string index starts with 0.

Example


#include <stdio.h>
int main() {
 char str[10]="ScholarHat";
 printf("%c", str[5]);
 return 0;
}

Output

a

%c is a format specifier to print a single character.

How to modify a String in C?

To change any specific character in a string, refer to the index number the same as an array. Here you also need to use single quotes,''.

Example


#include <stdio.h>
int main() {
 char str[10]="ScholarHat";
 str[4] = 'i';
 printf("%s", str);
 return 0;
}

Output

SchoiarHat

How to loop through a string in C?

To loop through a string, for loop is used.

Example


#include <stdio.h>
int main() {
 char str[10]="ScholarHat";
 
 for (int i = 0; i < 10; ++i) {
 printf("%c\n", str[i]);
 }
 return 0;
}

Output

S
c
h
o
l
a
r
H
a
t

String Functions in C

In C programming language, several string functions can be used to manipulate strings. To use them, you must include the <string.h> header file in your program. Here are some of the commonly used string functions in C:

  • strlen(): This function is used to find the length of a string. It takes a string as input and returns the number of characters in the string (excluding the null character).
  • strcpy(): This function is used to copy one string to another. It takes two arguments, the first argument is the destination string where the source string will be copied and the second argument is the source string.
  • strcat(): This function is used to concatenate two strings. It takes two arguments, the first argument is the destination string where the source string will be appended and the second argument is the source string.
  • strcmp(): This function is used to compare two strings. It takes two arguments, the first argument is the first string and the second argument is the second string. It returns an integer value that indicates the result of the comparison.
  • strchr(): This function is used to find the first occurrence of a character in a string. It takes two arguments, the first argument is the string and the second argument is the character to be searched. It returns a pointer to the first occurrence of the character in the string.

Example to demonstrate some basic string functions in C Online Compiler


#include <stdio.h>
#include <string.h>

int main() {
 // Declaration and Initialization
 char str1[] = "ScholarHat";
 char str2[20];
 char search = 'o';

 // strlen - String Length
 printf("Length of str1: %lu\n", strlen(str1));

 // strcpy - String Copy
 strcpy(str2, str1);
 printf("After copying, str2: %s\n", str2);

 // strcat - String Concatenation
 strcat(str2, " welcomes");
 printf("After concatenation, str2: %s\n", str2);

 // strcmp - String Comparison
 int result = strcmp(str1, str2);
 if (result == 0) {
 printf("str1 is equal to str2\n");
 } else if (result < 0) {
 printf("str1 is less than str2\n");
 } else {
 printf("str1 is greater than str2\n");
 }

 // strchr
 char *found = strchr(str1, search);
 // Check if the character is found
 if (found != NULL) {
 printf("'%c' found at position: %ld\n", search, found - str1 + 1);
 } else {
 printf("'%c' not found in the string.\n", search);
 }

 return 0;
}

Output

Length of str1: 10
After copying, str2: ScholarHat
After concatenation, str2: ScholarHat welcomes
str1 is less than str2
'o' found at position: 4
Summary

Strings in C can be quite challenging for some but with a little understanding of their components, anyone can quickly become proficient. From learning the basics of fundamental string operations such as concatenation there’s much to explore and understand. If you want to become proficient in the concepts of C programming, consider joining our C Certification course.

Share Article
Batches Schedule
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Self-paced Membership
  • 22+ Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A
  • 10+ Real-world Projects
  • Career Coaching
  • Email Support
Upto 66% OFF
KNOW MORE..

To get full access to all courses

Accept cookies & close this