Strings in C – String manipulation in C

This article is a Series on the C programming tutorial and carries the discussion on C language programming and its implementation. In our last tutorial, we have seen Arrays in C programming. This article explains the Strings in C programming. It aims to provide easy and practical examples for understanding the C program.

What are Strings in C Programming?

In the world of programming, strings are an essential component of any language. Strings are essentially a sequence of characters, and they play a crucial role in storing and manipulating text-based data. In the C programming language, strings are represented as arrays of characters and are null-terminated, meaning they end with a special character called the null character (\0), indicating the end of the string.

STRING

For example, the string “EmbeTronicX” can be represented as an array of characters enclosed in single quotes.

char str[] = {'E', 'm', 'b', 'e', 'T', 'r', 'o', 'n', 'i', 'c', 'X', '\0'};

The total number of characters in the string is 12,(11 characters with the null character). We can also represent a string using a string literal, which is a sequence of characters enclosed in double-quotes.

char str[] = "EmbeTronicX";

Types of Strings?

  • Alphabets String (It contains only alphabets)
  • Numerical String (It contains only Numbers)
  • Alphanumerical String (It contains only alphanumerical)

Syntax

char string_name[size];

Declaring and Initializing Strings

A string can be declared in C programming using either a character array or a character pointer. Here are some examples.

Declare using array

To declare a string in C, you can use the char data type and specify the size of the array. For example, to declare a string with a maximum length of 50 characters, you can write:

char str[51];

In this case, the array has a size of 51 to accommodate the null character at the end of the string. It is important to note that the size of the array should be one character more than the desired length of the string.

How to initialize the string

There are many ways to initialize the strings. Few of them are,

char *str = "EmbeTronicX";                                                   //Assigning a string with a pointer
char str[] = "EmbeTronicX";                                                 //Assigning a string without a size
char str[50] = "EmbeTronicX";                                               //Assigning a string with a predefined size
char str[] = {'E', 'm', 'b', 'e', 'T', 'r', 'o', 'n', 'i', 'c', 'X' '\0'};  //Assigning character without a size.
char str[12] = {'E', 'm', 'b', 'e', 'T', 'r', 'o', 'n', 'i', 'c', 'X' '\0'}; //Assigning character with a size.

Reading and Printing Strings

To read a string from the user, you can use the scanf function with the %s format specifier. For example:

char str[50];
printf("Enter a string: ");
scanf("%s", str);

You can also get the string using gets(). The gets() function in C is used to read a string from the standard input and store it in a character array.

The main difference between gets() and scanf() lies in their functionality and usage. gets() continues to read until a newline or End Of File(EOF) character is encountered. Unlike gets(), scanf() stops reading when it encounters whitespace, newline or End Of File(EOF).

To print a string, you can use the printf function with the %s format specifier. For example:

char str[] = "Hello, World!";
printf("String: %s", str);

You can also use puts() function to print.

How to modify the strings in C programming?

To change a specific character in a string, use the index number where you want to change and add the character with single quotes.

char str[] = "Kite";
str[0] = 'B';
printf("%s", str);
// Outputs Bite instead of Kite

Example Program

The below example program explains the traversing the string using a while loop.

#include <stdio.h>
#include <string.h>
int main()
{
    int i;
    char str[20];
    printf("Enter Strings:- ");
    scanf("%s",str);
    i=0;
    while(str[i]!='\0')
    {
        printf("%c,",str[i]);
        i++;
    }
}

Output

Enter Strings:- EmbeTronicX India
E,m,b,e,T,r,o,n,i,c,X,

Passing Strings to Functions

To pass a string to a function, we can use either using pointer or an array. The below program explains both methods.

#include<stdio.h> 

void modifyStringByArray(char str[]) 
{
    str[0] = 'H';  // modifying the first character of the string
}

void modifyStringByPointer(char *str) 
{
    str[0] = 'W';  // modifying the first character of the string
}

int main() 
{
    char myString_1[10] = "hello";
    char myString_2[10] = "welcome";
    printf("Before Modification: %s\n", myString_1);
    modifyStringByArray(myString_1);
    printf("After modifyStringByArray: %s\n", myString_1);

    printf("Before Modification: %s\n", myString_2);
    modifyStringByPointer(myString_2);
    printf("After modifyStringByPointer: %s\n", myString_2);
    return 0;
}

In the above source code, we have two functions (modifyStringByArray, modifyStringByPointer). Both are doing the same work and are technically the same. They are changing the first character of the given string.

Before Modification: hello
After modifyStringByArray: Hello
Before Modification: welcome
After modifyStringByPointer: Welcome

Passing strings to functions in C is a powerful feature that allows us to manipulate or analyze the contents of a string.

Array of strings in C

An array of strings in C is a powerful data structure that allows programmers to store and manipulate multiple strings in a single variable. In C, an array is a collection of elements of the same type that are stored in contiguous memory locations. Similarly, an array of strings is a collection of strings, where each string is stored in a separate memory location. These memory locations are accessed using indices, which represent the position of each string in the array.

To declare an array of strings in C, you need to specify the number of strings it can hold and the maximum length of each string. For example, to declare an array of five strings with a maximum length of 20 characters, you would write:

char strings[5][20];

In this declaration, ‘char‘ represents the data type of each character in a string, ‘strings‘ is the name of the array, ‘5’ is the number of strings it can hold, and ’20’ is the maximum length of each string.

Let’s consider an example to demonstrate the usage of an array of strings in C. Suppose you want to store the names of five students and display them on the screen. You can use an array of strings to achieve this. Here’s how you can do it:

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

int main() 
{
   char names[5][20];
   int i;

   for(i = 0; i < 5; i++) 
   {
      printf("Enter the name of student %d: ", i+1);
      scanf("%s", names[i]);
   }

   printf("\n\nNames of students:\n");
   for(i = 0; i < 5; i++) 
   {
      printf("%d. %s\n", i+1, names[i]);
   }

   return 0;
}

In this example, we declare an array of strings called ‘names‘ with a maximum length of 20 characters. We then use a loop to prompt the user to enter the names of five students, which are stored in the ‘names‘ array. Finally, we use another loop to display the names of the students on the screen.

Output:

Enter the name of student 1: Liyanshi
Enter the name of student 2: EmbeTronicX
Enter the name of student 3: Sunil
Enter the name of student 4: Kumar
Enter the name of student 5: Das

Names of students:
1. Liyanshi
2. EmbeTronicX
3. Sunil
4. Kumar
5. Das

Arrays of strings in C provide a flexible and efficient way to store and manipulate multiple strings. They are extensively used in various programming tasks, such as storing file names, command-line arguments, and text processing. Understanding how to work with arrays of strings is essential for any C programmer and can greatly enhance their ability to handle and manipulate textual data efficiently.

String Manipulation in C Programming

C provides various built-in functions that can be used to manipulate strings. These functions are defined in the standard C library <string.h> and are used to perform various operations on strings, such as copying, concatenating, comparing, searching, etc.

These are the commonly used in-built functions.

FunctionDescription
strlen()returns the string length
strcpy()copies a string to another string
strcat()joins two strings
strcmp()compares two strings
strrev()reverse the given string
strlwr()converts a string to lowercase
strupr()converts a string to uppercase

There are many other functions available. Please refer to string.h. Let’s see the example of all these strings using inbuilt functions one by one in C programming.

strlen()

strlen() function returns the length of the given string. It doesn’t count the null character ‘\0‘.

#include <stdio.h>
#include <string.h>
int main()
{
    int i;
    char str[100];
    printf("Enter a String:- ");
    gets(str);
    
    i = strlen(str);
    printf("Length = %d",strlen(str));
    return 0;
}

Output

Enter a String:- EmbeTronicX
Length = 11

strcpy()

strcpy() function copies the source string in the destination.

#include <stdio.h>
#include <string.h>
int main()
{
    char str1[100],str2[100];
    printf("Enter a String:- ");
    gets(str1);
    
    strcpy(str2,str1);
    printf("String Copied is %s",str1);
    return 0;
}

Output

Enter a String:- EmbeTronicX
String Copied is EmbeTronicX

strcat()

strcat() function concatenates two strings, the first string, and the second string, and the result is returned to the first string.

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

int main()
{
    int i;
    char str1[100],str2[100];
    printf("Enter First String:- ");
    gets(str1);
    printf("Enter Second String:- ");
    gets(str2);
    
    strcat(str1,str2);
    printf("Concatination is %s",str1);
}

Output

Enter First String:- EmbeTronicX
Enter Second String:- India
Concatination is EmbeTronicXIndia

strcmp()

strcmp() function compares two strings and returns 0 if both strings are equal.

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

int main()
{
    int i;
    char str1[100],str2[100];
    printf("Enter First String:- ");
    gets(str1);
    printf("Enter Second String:- ");
    gets(str2);
    
    i=strcmp(str1,str2);
    if(i==0)
    printf("String are same");
    else
    printf("String are not same");
}

Output 1

Enter First String:- EmbeTronicX
Enter Second String:- India
String are not same

Output 2

Enter First String:- EmbeTronicX
Enter Second String:- EmbeTronicX
String are same

If you don’t want to use the built-in function for string manipulation, you can implement your own function to do those operations.

In conclusion, strings are an integral part of C programming. They allow programmers to work with text-based data efficiently. By understanding the basics of string manipulation in C and utilizing the built-in functions, programmers can effectively handle and manipulate strings to meet their programming needs.

In our next tutorial, we will discuss the Structures in C programming (Structure, Structure Padding, Packing, Bit fields, etc).

You can also read the below tutorials.

Linux Device Driver TutorialsC Programming Tutorials
FreeRTOS TutorialsNuttX RTOS Tutorials
RTX RTOS TutorialsInterrupts Basics
I2C Protocol – Part 1 (Basics)I2C Protocol – Part 2 (Advanced Topics)
STM32 TutorialsLPC2148 (ARM7) Tutorials
PIC16F877A Tutorials8051 Tutorials
Unit Testing in C TutorialsESP32-IDF Tutorials
Raspberry Pi TutorialsEmbedded Interview Topics
Reset Sequence in ARM Cortex-M4BLE Basics
VIC and NVIC in ARMSPI – Serial Peripheral Interface Protocol
STM32F7 Bootloader TutorialsRaspberry PI Pico Tutorials
STM32F103 Bootloader TutorialsRT-Thread RTOS Tutorials
Zephyr RTOS Tutorials – STM32Zephyr RTOS Tutorials – ESP32
AUTOSAR TutorialsUDS Protocol Tutorials
Product ReviewsSTM32 MikroC Bootloader Tutorial
VHDL Tutorials
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Table of Contents