Strings in C Programming Language

Strings in C Programming Language: Strings in C are fundamental to managing text data. By using arrays of characters and a variety of string manipulation functions, C allows efficient string handling. Understanding both built-in functions and manual operations can make your code versatile and efficient.

C Programming Video Tutorial Lecture-06

In C programming, a string is essentially a collection of characters stored in a contiguous memory location, terminated by a null character (\0). Strings are arrays of characters but treated differently for various operations.

In C, strings are declared as arrays of characters. You can declare a string in two ways:

char str[10] = “Hello”;

Here, str can store up to 9 characters, plus the null terminator (\0).

char *str = “Hello”;

This creates a pointer to a string literal.

C strings are always terminated by a special character called the null terminator, represented as \0. This signifies the end of the string and allows functions to determine where the string ends.

You can read a string from the user using scanf or gets functions.

Using scanf:

char str[100];
scanf(“%s”, str);
The problem with scanf is that it stops reading input when it encounters a whitespace character (space, tab, newline).

Using gets:

char str[100];
gets(str);
gets reads the entire line, including spaces, but is unsafe as it doesn’t check buffer overflow.

Using fgets (Safe way):

char str[100];
fgets(str, 100, stdin);
fgets allows you to specify the maximum number of characters to read and is a safer alternative.

Printing a String

You can print a string using the printf function.

printf(“%s”, str);

C provides a set of built-in functions for performing various string operations. These functions are declared in the string.h header file.

strlen() – Find the length of a string:

int length = strlen(str);
This function returns the number of characters in the string, excluding the null terminator.

strcpy() – Copy one string into another:

strcpy(destination, source);
This function copies the content of the source string into the destination.

strcat() – Concatenate two strings:

strcat(destination, source);
This function appends the source string to the destination string.

strcmp() – Compare two strings:

int result = strcmp(str1, str2);
This function compares two strings. If the strings are equal, it returns 0. If str1 is greater than str2, it returns a positive value, and if str1 is less than str2, it returns a negative value.

strncpy() – Copy a specified number of characters:

strncpy(destination, source, n);
This function copies n characters from the source string to the destination string.

strncat() – Concatenate a specified number of characters:

strncat(destination, source, n);
This function appends n characters from the source string to the destination string.

strchr() – Find the first occurrence of a character:

char *ptr = strchr(str, ‘a’);
This function returns a pointer to the first occurrence of the character a in the string.

strstr() – Find a substring within a string:

char *ptr = strstr(str, “world”);
This function returns a pointer to the first occurrence of the substring “world” in str.

You can also perform string operations manually without using built-in functions. For example, to find the length of a string:

int string_length(char str[]) {
int i = 0;
while (str[i] != ‘\0’) {
i++;
}
return i;
}

Example Program: Basic String Operations

#include<stdio.h>

#include<string.h>

int main() {
char str1[100], str2[100];

// Input strings
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);

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

// String copy
strcpy(str2, str1);
printf("After copying, second string: %s\n", str2);

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

// String comparison
if (strcmp(str1, str2) == 0) {
    printf("Strings are equal.\n");
} else {
    printf("Strings are not equal.\n");
}

return 0;

}

In C, when handling dynamic strings, you can use pointers with memory allocation functions like malloc and free from the stdlib.h library.

Example:

#include<stdio.h>

#include<string.h>

int main() {
char *str;

// Allocate memory for string
str = (char *)malloc(100 * sizeof(char));
if (str == NULL) {
    printf("Memory allocation failed\n");
    return 1;
}

// Input and output
printf("Enter a string: ");
gets(str);
printf("You entered: %s\n", str);

// Free allocated memory
free(str);

return 0;

}

In C, a string can also be manipulated using a pointer to a character. For instance, you can traverse a string using a pointer.

Example:

#include<stdio.h>

int main() {
char str[] = “Hello”;
char *ptr = str;

// Traverse string using pointer
while (*ptr != '\0') {
    printf("%c", *ptr);
    ptr++;
}

return 0;

}

Q1: What is a string in C?

A string in C is a sequence of characters terminated by a null character (\0). It is essentially an array of characters, where the last element is always the null terminator that signals the end of the string.

Q2: How do you declare a string in C?

A string can be declared in two ways:
As a character array:
char str[10] = “Hello”;
Using a pointer to a string literal:
char *str = “Hello”;

Q3: What is the difference between character arrays and string literals?

A character array stores the string in a modifiable memory location, while a string literal points to a fixed memory location (typically read-only), which means modifying a string literal may lead to undefined behavior.

Q4: What is the purpose of the null character (\0) in a string?

The null character (\0) indicates the end of the string. It tells string functions like strlen() and printf() where the string stops.

Q5: How do you input a string from the user?

You can use functions like scanf(), gets(), or the safer alternative fgets() to take string input:
scanf() stops reading at the first whitespace.
gets() reads the entire line but is unsafe due to possible buffer overflow.
fgets() is safe and allows you to specify the buffer size.
Example:
char str[100];
fgets(str, 100, stdin);

Q6: What are the most commonly used string functions in C?

Some of the most commonly used string manipulation functions (from string.h) are:
strlen() – Returns the length of the string.
strcpy() – Copies one string to another.
strcat() – Concatenates two strings.
strcmp() – Compares two strings.
strncpy() – Copies a specified number of characters.
strchr() – Finds the first occurrence of a character in a string.
strstr() – Finds a substring within a string.

Q7: What is the difference between strcpy() and strncpy()?

strcpy(destination, source) copies the entire source string into destination, including the null terminator.
strncpy(destination, source, n) copies only the first n characters from source to destination, and does not automatically append a null character unless n is smaller than the string length.

Q8: How do you concatenate two strings in C?

You can concatenate two strings using the strcat() function. The source string is appended to the destination string.
char dest[100] = “Hello “;
char src[] = “World”;
strcat(dest, src); // dest becomes “Hello World”

Q9: How do you compare two strings in C?

The strcmp() function is used to compare two strings. It returns:
0 if the strings are equal.
A positive value if the first string is greater than the second.
A negative value if the first string is less than the second.
int result = strcmp(str1, str2);

Q10: What is the difference between scanf() and gets() for reading strings?

scanf() reads a string until it encounters a whitespace (space, tab, newline), which means it cannot read multiple words.
gets() reads the entire line, including spaces, but it is unsafe and can cause buffer overflows.

Q11: Why is fgets() preferred over gets()?

fgets() is safer because it prevents buffer overflow by allowing the programmer to specify the maximum number of characters to read. Unlike gets(), it also stops reading at the newline or end of the buffer.

Q12: Can you modify string literals in C?

No, string literals in C are stored in a read-only memory location. Attempting to modify a string literal can lead to undefined behavior.

Q13: How do you find the length of a string?

You can use the strlen() function to find the length of a string. It returns the number of characters in the string, excluding the null terminator.
int length = strlen(str);
Previous

Learn More

Subscribe “JNG ACADEMY” for more learning best content.

C Programming Language Lecture-01

C Programming Language Lecture-02

C Programming Language Lecture-03

C Programming Language Lecture-04

C Programming Language Lecture-05

C Programming Language Lecture-06

C Programming Language Youtube Playlist

Thank You So Much, Guys… For Visiting our Website and Youtube.

Leave a Comment