DEV Community

Cover image for How to use Strings in C Programming
AbdulKarim
AbdulKarim

Posted on • Updated on

How to use Strings in C Programming

In this comprehensive C strings tutorial, my primary goal is to guide you through the fundamentals how to use strings in c from the ground up. By the end of this tutorial, you will have gained an in-depth understanding of the following fundamental topics:

  • Understanding Strings:
  • Character Arrays vs. String Literals.
  • Null Terminating Character.
  • String Input and Output Functions.
  • String Manipulation Functions.

Prerequisite: To derive maximum benefit from this tutorial, it is recommended that you possess a comfortable understanding of basic C programming concepts, including variables, data types, functions, and arrays.

Understanding Strings:

Strings in C are manipulated using arrays of characters. Each character in the array corresponds to an element of the string, and the end of the string is marked by the null character ('\0'). This null character is crucial as it signifies the end of the string and allows functions to determine where the string ends in memory.

For example, the string "hello" is represented as:

char str[] = {'h', 'e', 'l', 'l', 'o', '\0'};
Enter fullscreen mode Exit fullscreen mode

This array str holds characters of the string "hello" and ends with the null character '\0' indicating the string's termination.

Another common representation is using string literals:

char str[] = "hello";
Enter fullscreen mode Exit fullscreen mode

In this case, the compiler automatically appends the null character '\0' at the end of the string.

Character Arrays vs. String Literals:

Character Arrays:
You create them by defining the size of the array and Initialize individual characters.
For example:

char name[5] = {'J', 'o', 'h', 'n', '\0'};
Enter fullscreen mode Exit fullscreen mode

This creates a character array named name that can hold up to 6 characters (including the null terminator '\0') and explicitly assigns each character.

String Literals:

Represented by enclosing characters within double quotes: This is a shorter and more convenient way to represent strings.
Compiler appends the null character ('\0') automatically: For example:

char greeting[] = "Hello";
Enter fullscreen mode Exit fullscreen mode

Here, the compiler determines the size of the array based on the length of the string literal "Hello" and automatically adds the null terminator '\0'.

Null Terminating Character '\0':

The null character ('\0') is a special character in C used to mark the end of a string. It has a value of 0 in ASCII.

In C, strings are terminated by this null character to indicate the end of the string's contents. It's crucial for functions that process strings to know where the string ends. For example, when you use functions like strlen() to determine the length of a string, it calculates the length by counting characters until it encounters the null character.

For instance:

char message[] = "Hello";
Enter fullscreen mode Exit fullscreen mode

This string "Hello" is stored as 'H', 'e', 'l', 'l', 'o', '\0'.
Without the null character, C functions that operate on strings would not know where the string ends, leading to undefined behavior or unexpected results.

String Input and Output Functions:

Using printf() for Output:

The printf() function is used to print strings to the standard output (usually the console).

Example:

#include <stdio.h>

int main() {
    char str[] = "Hello";
    printf("The string is: %s\n", str);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

The string is: Hello
Enter fullscreen mode Exit fullscreen mode

Using scanf() for Input:

The scanf() function is used to read strings from the standard input (keyboard).

Example:

#include <stdio.h>

int main() {
    char name[20];
    printf("Enter your name: ");
    scanf("%s", name);
    printf("Hello, %s!\n", name);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Input:

Enter your name: Kareem
Enter fullscreen mode Exit fullscreen mode

Output:

Hello, Kareem!
Enter fullscreen mode Exit fullscreen mode

Note: scanf("%s", name) reads a string from the user's input, but it stops at the first whitespace character (space, tab, newline).

Using fgets() for Input:

The fgets() function reads a line of text from the standard input, allowing spaces in the input.

Example:

#include <stdio.h>

int main() {
    char sentence[50];
    printf("Enter a sentence: ");
    fgets(sentence, sizeof(sentence), stdin);
    printf("You entered: %s", sentence);
    return 0;
}

Enter fullscreen mode Exit fullscreen mode

Input:

Enter a sentence: This is a sentence with spaces.
Enter fullscreen mode Exit fullscreen mode

Output:

You entered: This is a sentence with spaces.
Enter fullscreen mode Exit fullscreen mode

These examples demonstrate how printf(), scanf(), and fgets() functions can be used for string input and output in C, allowing interaction with strings during program execution.

String Manipulation Functions:

In C, there's a set of functions provided by the header that allow manipulation of strings. Some of the commonly used functions include:

  • strcpy(): This function copies the characters from the source string to the destination string until it encounters the null character ('\0') in the source string. Example:
#include <stdio.h>
#include <string.h>

int main() {
    char source[] = "Hello";
    char destination[20];

    strcpy(destination, source);
    printf("Destination string after copying: %s\n", destination);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

Destination string after copying: Hello
Enter fullscreen mode Exit fullscreen mode
  • strcat():This function concatenate (appends) the content of the source string to the end of the destination string. It starts at the null character ('\0') of the destination string and copies characters from source until it encounters its null character.

Example:

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

int main() {
    char str1[20] = "Hello";
    char str2[] = " World";

    strcat(str1, str2);
    printf("Concatenated string: %s\n", str1);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

Concatenated string: Hello World
Enter fullscreen mode Exit fullscreen mode
  • strlen(): This function returns the number of characters in the string str, excluding the null character ('\0'). Example:
#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "Hello";
    int length = strlen(str);

    printf("Length of the string: %d\n", length);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

Length of the string: 5
Enter fullscreen mode Exit fullscreen mode

Here are some additional common string operations in C:

strcmp(): This function compares the contents of str1 and str2 and returns:

  • 0 if both strings are equal.
  • a value less than 0 if str1 is less than str2.
  • a value greater than 0 if str1 is greater than str2. Example:
char str1[] = "apple";
char str2[] = "banana";
int result = strcmp(str1, str2);
Enter fullscreen mode Exit fullscreen mode

strncpy():This function Copies a specific number of characters from one string to another. The below example Copies at most num characters from source to destination:

char source[] = "Hello";
char destination[10];
strncpy(destination, source, 3); // Copies only 3 characters
Enter fullscreen mode Exit fullscreen mode

you can find more string operations by visiting w3resource

In conclusion, Through this tutorial, we've delved into the intricacies of handling strings, from understanding their fundamental nature to implementing various manipulation techniques.

By familiarizing yourself with character arrays, string literals, null-terminating characters, input/output functions, and manipulation functions, you've laid a strong foundation for utilizing strings effectively in your C programs.

Should you have any queries or require further clarification on any aspect covered in this tutorial, please feel free to drop your questions. I'm here to assist and ensure your understanding.

Thanks for reading and understanding. That's all for now, and I will catch you on the next one!

Top comments (2)

Collapse
 
pauljlucas profile image
Paul J. Lucas

You can also use puts() and fputs() for string output (which are better when no interpolation is needed). Using fgets() is better for string input.

You neglected to mention the serious issue of buffer overflows with strcpy() and strcat() β€” and no, strncpy() is not a safer alternative. The true safer alternatives are strlcpy() and strlcat().

You neglected to mention dynamically allocating and freeing strings.

Your example:

char name[6] = {'J', 'o', 'h', 'n', '\0'};
Enter fullscreen mode Exit fullscreen mode

has the array 1 character bigger than it needs to be.

Collapse
 
koderkareem profile image
AbdulKarim

Thank you for your feedback. I've rectified the character array issue with name[6] and will update the rest accordingly.

Your insights on puts(), fputs(), and fgets() are noted. I'll include safer alternatives like strlcpy() and strlcat() to address buffer overflow concerns.

Dynamic memory allocation and freeing strings will also be covered

Thank you once again for your valuable feedback.