String in C

String in C. String in C Tutorial. Learn String in C
String in C

What is String in C ?

In C, a string is an array of characters terminated by a null character (‘\0’). It is used to store and manipulate sequences of characters.

Strings are used in C for various purposes, such as storing and manipulating text, reading input from the user, and displaying output. They provide a convenient way to work with textual data.

Syntax:

char string_name[size];

Here, string_name is the name of the string variable, and size is the maximum number of characters that the string can hold, including the null character.

Different ways to declare a string in C

1. Array Declaration

Example:

#include <stdio.h>

int main() {
    char str1[10] = "Pokemon";
    printf("%s\n", str1);
    return 0;
}

Output:

Pokemon

Explanation:

In above example, str1 is declared as an array of characters with a size of 10. The string “Hello” is assigned to str1, and it is printed using %s format specifier.

2. String Literal Assignment

Example:

#include <stdio.h>

int main() {
    char str2[] = "Water";
    printf("%s\n", str2);
    return 0;
}

Output:

Water

Explanation:

In above example, str2 is declared without specifying the size. The string “World” is assigned to str2, and it is printed using %s format specifier.

3. Pointer Declaration

Example:

#include <stdio.h>

int main() {
    char *str3 = "Jello";
    printf("%s\n", str3);
    return 0;
}

Output:

Jello

Explanation:

In above example, str3 is declared as a pointer to a character. The string “Hello” is assigned to str3, and it is printed using %s format specifier.

More about strings in C

1. Assigning new values

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

int main() {
    char str[10] = "Hello";
    printf("Original string: %s\n", str);
    
    strcpy(str, "Goodbye");
    printf("Modified string: %s\n", str);
    
    return 0;
}

Output:

Original string: Hello
Modified string: Goodbye

Explanation:

In above example, the original string str is assigned the value “Hello”. Later, the strcpy() function is used to assign a new value “Goodbye” to the string str. The strcpy() function copies the contents of the second string to the first string, effectively replacing the original value. The modified string is then printed.

2. Concatenation

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

int main() {
    char str1[20] = "Hello";
    char str2[] = " World";
    
    printf("Original strings: %s\n", str1);
    
    strcat(str1, str2);
    printf("Concatenated string: %s\n", str1);
    
    return 0;
}

Output:

Original strings: Hello
Concatenated string: Hello World

Explanation:

In above example, two strings str1 and str2 are declared. The strcat() function is used to concatenate str2 to the end of str1. The resulting string contains both “Hello” and “World”. The concatenated string is then printed.

3. Comparison

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

int main() {
    char str1[] = "apple";
    char str2[] = "banana";
    
    int result = strcmp(str1, str2);
    
    if (result < 0) {
        printf("%s comes before %s\n", str1, str2);
    } else if (result > 0) {
        printf("%s comes after %s\n", str1, str2);
    } else {
        printf("%s is equal to %s\n", str1, str2);
    }
    
    return 0;
}

Output:

apple comes before banana

Explanation:

In above example, two strings str1 and str2 are declared. The strcmp() function is used to compare the two strings. It returns a negative value if str1 comes before str2 in lexicographic order, a positive value if str1 comes after str2, and 0 if they are equal. Based on the comparison result, the appropriate message is printed.

4. Modification of Individual Characters

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

int main() {
    char str[] = "Hello";
    printf("Original string: %s\n", str);
    
    str[0] = 'J';
    printf("Modified string: %s\n", str);
    
    return 0;
}

Output:

Original string: Hello
Modified string: Jello

Explanation:

In above example, the original string str is declared as “Hello”. The individual character at index 0, which is ‘H’, is modified to ‘J’ by assigning the new character to str[0]. The modified string is then printed, showing the change of the first character from ‘H’ to ‘J’.

One Big Fat Example of string in C

In below example, we have a text processing system that takes user input as text and performs three operations on it.

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

#define MAX_TEXT_SIZE 1000

void removeSpaces(char* text) {
    int length = strlen(text);
    int i, j;
    
    for (i = 0, j = 0; i < length; i++) {
        if (text[i] != ' ') {
            text[j] = text[i];
            j++;
        }
    }
    
    text[j] = '\0';
}

void reverseText(char* text) {
    int length = strlen(text);
    int i, j;
    
    for (i = 0, j = length - 1; i < j; i++, j--) {
        char temp = text[i];
        text[i] = text[j];
        text[j] = temp;
    }
}

int countOccurrences(char* text, char* pattern) {
    int count = 0;
    int patternLength = strlen(pattern);
    int textLength = strlen(text);
    
    if (patternLength > textLength)
        return 0;
    
    for (int i = 0; i <= textLength - patternLength; i++) {
        int j;
        
        for (j = 0; j < patternLength; j++) {
            if (text[i + j] != pattern[j])
                break;
        }
        
        if (j == patternLength)
            count++;
    }
    
    return count;
}

int main() {
    char text[MAX_TEXT_SIZE];
    printf("Enter the text: ");
    fgets(text, MAX_TEXT_SIZE, stdin);
    
    // Remove spaces from the text
    removeSpaces(text);
    printf("Text without spaces: %s\n", text);
    
    // Reverse the text
    reverseText(text);
    printf("Reversed text: %s\n", text);
    
    // Count occurrences of a pattern in the text
    char pattern[MAX_TEXT_SIZE];
    printf("Enter the pattern to count occurrences: ");
    fgets(pattern, MAX_TEXT_SIZE, stdin);
    pattern[strcspn(pattern, "\n")] = '\0'; // Remove newline character from pattern
    
    int occurrences = countOccurrences(text, pattern);
    printf("Occurrences of '%s': %d\n", pattern, occurrences);
    
    return 0;
}

Output:

Enter the text: Hello World!
Text without spaces: HelloWorld!
Reversed text: !dlroWolleH
Enter the pattern to count occurrences: l
Occurrences of 'l': 3

Explanation:

  1. removeSpaces() function is used to remove spaces from the input text. It iterates through each character of the text, skips spaces, and copies non-space characters to a new position. Finally, it adds a null character at the end to terminate the string.
  2. reverseText() function reverses the text by swapping characters from the beginning and end of the string. It uses two pointers, one pointing to the start and the other to the end of the string, and gradually swaps characters until they meet in the middle.
  3. countOccurrences() function counts the occurrences of a given pattern in the text. It iterates through the text and checks if the pattern matches at each position. If a match is found, the count is incremented. It returns the total count of occurrences.

The user is prompted to enter the input text and a pattern. The system then performs the operations on the text and displays the results.

In the output, the input text “Hello World!” is processed. Spaces are removed, resulting in “HelloWorld!”. The text is then reversed to “!dlroWolleH”. Finally, the system asks for a pattern “l” and counts its occurrences in the text, which is 3.

More: