top

Search

C Tutorial

.

UpGrad

C Tutorial

String Functions in C

As an integral part of any programming language, strings in C play a significant role in storing and manipulating sequences of characters. Strings in C are depicted as an array of characters that concludes with a null character ('\0'). However, C does make up for this by offering a wide selection of string functions via the standard library, enhancing your code's clarity and efficiency.

This in-depth article will explore various string functions in C, provide examples and explain each section comprehensively. We'll delve into a range of concepts, including the array of strings in C, scanf string in C, and string input in C.

String Declaration

A C string is declared similarly to an array. Here's a basic demonstration:

char str[50] = "Hello, World!";

In this instance, str represents an array of characters, which is initialized using the string "Hello, World!". Essentially, the string is stored character by character in each index of the array, ending with a null character.

String Functions

Before delving into the various string functions in C, it's essential to understand how to prepare your program to use these functions.

In C programming, there's a standard library <string.h> which contains various functions to perform operations on strings. To use the functions declared in this library, you have to include them in your program. The inclusion is done with the preprocessor directive #include.

Here's how you include the <string.h> library in your C program:

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

In the code snippet above, <stdio.h> is the standard input-output library in C, which contains functions like printf() and scanf(). The <string.h> library, on the other hand, contains various string manipulation functions like strcpy(), strlen(), strcat(), etc.

Examples of String Functions in C

Here is an example illustrating the use of fundamental string functions:

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

int main() {
    char message1[15] = "Hello";
    char message2[10] = "World";
    char message3[20];
    int length;

    /* copy message1 into message3 */
    strcpy(message3, message1);
    printf("strcpy(message3, message1): %s\n", message3);

    /* concatenate message1 and message2 */
    strcat(message1, message2);
    printf("strcat(message1, message2): %s\n", message1);

    /* total length of message1 after concatenation */
    length = strlen(message1);
    printf("strlen(message1): %d\n", length);

    return 0;
}

In this code:

  1. We first initialize two strings, message1 and message2, with "Hello" and "World", respectively.

  2. Then we copy message1 into message3 using the strcpy() function.

  3. Next, strcat() function is used to concatenate message1 and message2, making message1 become "HelloWorld".

  4. Finally, we calculate and print the total length of message1 after concatenation using the strlen() function.

Character Array and String Functions

While C doesn't natively support a "String" data type, it's common to create strings using an array of characters. The scanf function can be used for string input in C, as demonstrated below:

#include<stdio.h>

int main() {
    char Inputstr[100];

    printf("Enter a string: ");
    scanf("%s", Inputstr);

    printf("You entered: %s", Inputstr);

    return 0;
}

In this code, we declare a character array str of size 100, prompting the user to input a string. 

Character Arrays

Character arrays are simply arrays that store individual characters. This example creates an array of five characters:

char c[5];

Difference between Character Arrays and Strings

The terms "character array" and "string" are often used interchangeably in C, but there are key differences between them.

A character array in C is simply an array of characters. You can declare it and initialize it with individual characters.

On the other hand, a string in C is a special type of character array that ends with a null character (\0). The null character is used to mark the end of the string. 

Initializing Strings

There are multiple ways to initialize strings in C. Here's a basic illustration:

char str1[] = "Hello"; // String literal initialization
char str2[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Array initialization

In the first declaration, str1 is automatically sized to hold the string literal and is initialized with "Hello". The second declaration manually specifies the array's size and initializes it with individual characters, including the null character at the end.

Accessing Strings

Individual characters within a string can be accessed using their array index:

char str[] = "Hello";
printf("%c\n", str[1]); // This will output 'e'

In this code, we're accessing the second character (at index 1, since C arrays are 0-indexed) of the string and printing it to the console.

String Manipulation Functions

Let's go over some of the most commonly used string manipulation functions.

strlen() Function

The strlen() function calculates the length of a string excluding the null terminating character. 

Example:

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

int main() {
   char Inputstr[50];
   int len;

   printf("Enter a string: ");
   gets(Inputstr);

   len = strlen(Inputstr);
   printf("Length of entered string is = %d", len);

   return(0);
}

This code asks the user for a string input, which it then measures using strlen(), printing out the length of the string to the console. 

strcat() Function

The strcat() function concatenates (joins end-to-end) two strings. 

Example:

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

int main() {
   char Inputstr1[50], Inputstr2[50];

   printf("Enter first string: ");
   gets(Inputstr1);

   printf("Enter second string: ");
   gets(Inputstr2);

   strcat(Inputstr1, Inputstr2);
   printf("String obtained on concatenation is %s", Inputstr1);

   return(0);
}

In this code, we're getting two strings as input from the user. We then concatenate the second string to the end of the first string using strcat(), effectively modifying the first string.

strcpy() Function

The strcpy() function is used to copy the content of one string into another. 

Example:

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

int main() {
   char sourceString[100], destinationString[100];

   printf("Enter source string: ");
   gets(sourceString);

   strcpy(destinationString, sourceString);
   printf("Destination string is: %s", destinationString);

   return(0);
}

In this example, we copy the content of the source string into the destination string using strcpy(). The content of the source string remains unchanged, and the destination string becomes identical to the source string.

strcmp() Function

The strcmp() function is used to compare two strings. It returns 0 if the strings are identical, a negative value if the first string is less than the second, and a positive value if the first string is greater than the second. 

Example:

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

int main() {
   char Inputstr1[100], Inputstr2[100];
   int result;

   printf("Enter first string: ");
   gets(Inputstr1);

   printf("Enter second string: ");
   gets(Inputstr2);

   result = strcmp(Inputstr1, Inputstr2);
   if(result == 0) {
      printf("Strings are equal.");
   } else {
      printf("Strings are not equal.");
   }

   return(0);
}

In this code, we take two strings from the user. We then use strcmp() to compare these strings and print a message depending on whether the strings are equal or not.

strncat() Function

The strncat() function is similar to strcat(), but it concatenates only the first n characters of the second string to the first string.

Example:

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

int main() {
   char Inputstr1[100], Inputstr2[100];
   int n;

   printf("Enter first string: ");
   gets(Inputstr1);

   printf("Enter second string: ");
   gets(Inputstr2);

   printf("Enter number of characters to concatenate: ");
   scanf("%d", &n);

   strncat(Inputstr1, Inputstr2, n);
   printf("String obtained on concatenation is %s", Inputstr1);

   return(0);
}

In this code, we get two strings and an integer n from the user. We then concatenate the first n characters of the second string to the first string using strncat().

strncpy() Function

The strncpy() function is used to copy the first n characters of one string into another.

Example:

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

int main() {
   char sourceString[100], destinationString[100];
   int n;

   printf("Enter source string: ");
   gets(sourceString);

   printf("Enter number of characters to copy: ");
   scanf("%d", &n);

   strncpy(destinationString, sourceString, n);
   destinationString[n] = '\0'; // Adding a null character at the end
   printf("Destination string is: %s", destinationString);

   return(0);
}

In this example, we copy the first n characters of the source string into the destination string using strncpy(). The remaining characters in the destination string, if any, are not modified.

strncmp() Function

The strncmp() function is used to compare the first n characters of two strings. It works in the same way as strcmp(), but the comparison stops after n characters. 

Example:

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

int main() {
   char Inputstr1[100], Inputstr2[100];
   int n, result;

   printf("Enter first string: ");
   gets(Inputstr1);

   printf("Enter second string: ");
   gets(Inputstr2);

   printf("Enter number of characters to compare: ");
   scanf("%d", &n);

   result = strncmp(Inputstr1, Inputstr2, n);
   if(result == 0) {
      printf("First %d characters of strings are equal.", n);
   } else {
      printf("First %d characters of strings are not equal.", n);
   }

   return(0);
}

In this code, we compare the first n characters of two user-entered strings using strncmp() and print a message depending on the result.

strchr() Function

The strchr() function is used to find the first occurrence of a character in a string. It returns a pointer to the character's location in the string, or NULL if the character is not found. 

Example:

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

int main() {
   char Inputstr[100], ch;
   char *result;

   printf("Enter a string: ");
   gets(Inputstr);

   printf("Enter a character to find: ");
   ch = getchar();

   result = strchr(Inputstr, ch);
   if(result != NULL) {
      printf("Character found at position %ld.", result-Inputstr+1);
   } else {
      printf("Character not found.");
   }

   return(0);
}

In this code, we find the first occurrence of a user-entered character in a user-entered string using strchr(). 

strstr() Function

The strstr() function is used to find the first occurrence of a substring in a string. It returns a pointer to the beginning of the located substring, or NULL if the substring is not found.

Example:

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

int main() {
   char Inputstr[100], sub[50];
   char *result;

   printf("Enter a string: ");
   gets(Inputstr);

   printf("Enter a substring to find: ");
   gets(sub);

   result = strstr(Inputstr, sub);
   if(result != NULL) {
      printf("Substring found at position %ld.", result-Inputstr+1);
   } else {
      printf("Substring not found.");
   }

   return(0);
}

In this code, we find the first occurrence of a user-entered substring in a user-entered string using strstr(). 

strtok() Function

The strtok() function is used to split a string into a series of tokens using a delimiter.

Example:

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

int main() {
   char Inputstr[100], delim[10];
   char *token;

   printf("Enter a string: ");
   gets(Inputstr);

   printf("Enter a delimiter: ");
   gets(delim);

   token = strtok(Inputstr, delim);
   while(token != NULL) {
      printf(" %s\n", token);
      token = strtok(NULL, delim);
   }

   return(0);
}

In this example, we split a user-entered string into tokens using a user-entered delimiter with strtok(). Each token is then printed on a new line.

sscanf() Function

The sscanf() function is used to read formatted input from a string. 

Example:

#include <stdio.h>

int main() {
   char Inputstr[] = "123 456";
   int a, b;

   sscanf(Inputstr, "%d %d", &a, &b);
   printf("The values are %d and %d.", a, b);

   return(0);
}

In this code, we read two integers from a string using sscanf(). The read values are then printed to the console.

String Formatting Functions

String formatting functions help to format strings in C. Let’s explore some of these functions.

sprintf() Function

The sprintf() function is used to store formatted data as a string. 

Example:

#include <stdio.h>

int main() {
   char buffer[50];
   int a = 10, b = 20;

   sprintf(buffer, "Sum of %d and %d is %d.", a, b, a+b);
   printf("%s", buffer);

   return(0);
}

In this code, we're storing the formatted string "Sum of 10 and 20 is 30." into the buffer using sprintf(). 

printf() Function

The printf() function is used to print formatted data to stdout (the console, by default). 

Example:

#include <stdio.h>

int main() {
   int l = 10, m = 20;

   printf("Sum of %d and %d is %d.", l, m, l+m);

   return(0);
}

In this example, we're printing the formatted string "Sum of 10 and 20 is 30." directly to the console using printf().

fprintf() Function

The fprintf() function is used to print formatted data to a file. 

Example:

#include <stdio.h>

int main() {
   FILE *file = fopen("test.txt", "w");
   int a = 10, b = 20;

   if(file != NULL) {
      fprintf(file, "Sum of %d and %d is %d.", a, b, a+b);
      fclose(file);
   }

   return(0);
}

In this code, we're printing the formatted string "Sum of 10 and 20 is 30." to a file named "test.txt" using fprintf().

Applications of String Functions

String functions in C play a significant role in various fields, including:

  1. Data Processing: String functions can be used to process and manipulate text data, such as reading, modifying, comparing, and sorting strings.

  2. File Handling: String functions, like fscanf(), fgets(), fprintf(), etc., are often used in reading from and writing to files.

  3. Communication Systems: String functions are widely used in communication systems for encoding, decoding, and transmitting data.

  4. Database Systems: In database systems, string functions are used to manipulate and process database records.

Conclusion

String functions in C offer a powerful and flexible way to manipulate, process, and interact with character strings. Understanding these functions will significantly enhance your capability to write efficient and powerful C programs. Now it's your turn to experiment with these functions. Practice makes perfect!

Which is why enrolling in upGrad’s DevOps Engineer Bootcamp can greatly contribute to the well-being of your professional career, helping skyrocket your professional growth! 

FAQs

1. What is a string in C, and how can I use it?

A string in C can be referred to as a character array ending with a null character (\0). To declare a string in C, you can either initialize it directly: char str[] = "Hello"; or declare an array to hold the string: char str[100]; and then input the string using functions like gets(), scanf(), etc.

2. Can I perform operations on strings in C?

Yes, you can perform various operations on strings in C using string functions. These operations include copying a string (strcpy()), concatenating two strings (strcat()), comparing two strings (strcmp()), finding the length of a string (strlen()), and many more.

3. How do I take a string input in C?

You can take string input in C using functions like scanf(), gets(), fgets(), etc. Be careful while using scanf(), as it terminates the input on encountering a space. So, for a sentence input, gets() or fgets() are more suitable.

Leave a Reply

Your email address will not be published. Required fields are marked *