String in C

What is String in C ?

In C, a string is an array of characters terminated by a null character ('\0'). This null character marks the end of the string and helps in distinguishing the boundary between strings. Strings in C are often manipulated using pointers, making them a versatile data type.

Declaring and Initializing Strings

To declare a string in C, you create a character array and initialize it with the desired sequence of characters. For example:

char greeting[] = "Hello, World!";

Accessing Individual Characters

Individual characters in a string can be accessed using their index. The first character is at index 0, the second at index 1, and so on. For instance:

char firstChar = greeting[0]; // 'H'

String Manipulation Functions

C provides several built-in functions to manipulate strings effectively. Lets see a few of them: (we will see all string functions in next chapter)

Concatenating Strings

You can concatenate two strings using the strcat() function:

char firstName[] = "John";
char lastName[] = "Doe";
strcat(firstName, lastName); // firstName now contains "JohnDoe"

Comparing Strings

Use the strcmp() function to compare two strings:

if (strcmp(firstName, lastName) == 0) {
    // Strings are equal
} else {
    // Strings are not equal
}

Finding Substrings

The strstr() function helps you find the first occurrence of a substring within a string:

char sentence[] = "The quick brown fox";
char word[] = "brown";
char *ptr = strstr(sentence, word); // Points to "brown fox"

Extracting Substrings

You can extract a portion of a string using array indexing:

char source[] = "Programming is fun!";
char destination[10];
strncpy(destination, source + 12, 3); // Copies "fun" to destination
destination[3] = '\0'; // Null-terminate the extracted substring

Modifying Strings

Strings can be modified to suit your needs.

Changing Character Case

Transforming the case of characters can be done using loops:

char text[] = "Hello, World!";
for (int i = 0; text[i]; i++) {
    if (islower(text[i])) {
        text[i] = toupper(text[i]);
    } else if (isupper(text[i])) {
        text[i] = tolower(text[i]);
    }
}

Reversing a String

You can reverse a string by swapping characters from the beginning and end:

void reverseString(char str[]) {
    int length = strlen(str);
    for (int i = 0; i < length / 2; i++) {
        char temp = str[i];
        str[i] = str[length - i - 1];
        str[length - i - 1] = temp;
    }
}

Removing Whitespaces

Trimming whitespace characters from the beginning and end of a string can be achieved with the following function:

void trimWhitespace(char str[]) {
    int start = 0;
    while (isspace(str[start])) {
        start++;
    }
    int end = strlen(str) - 1;
    while (end > start && isspace(str[end])) {
        end--;
    }
    str[end + 1] = '\0';
    memmove(str, str + start, end - start + 2);
}

Input and Output of Strings

Reading Strings

You can read strings using the scanf() function:

char name[50];
scanf("%s", name);

Printing Strings

Strings are printed using the printf() function:

printf("Hello, %s!", name);

Examples:

Implementing a Palindrome Checker

A palindrome is a word, phrase, or sequence of characters that reads the same forwards and backwards. In this example, we’ll create a C function to check if a given string is a palindrome.

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

int isPalindrome(char str[]) {
    int length = strlen(str);
    for (int i = 0; i < length / 2; i++) {
        if (str[i] != str[length - i - 1]) {
            return 0; // Not a palindrome
        }
    }
    return 1; // Palindrome
}

int main() {
    char word[] = "radar";
    
    if (isPalindrome(word)) {
        printf("%s is a palindrome.\n", word);
    } else {
        printf("%s is not a palindrome.\n", word);
    }
    
    return 0;
}

Output and Explanation:

radar is a palindrome.

In this example, we define the isPalindrome function, which checks if a given string is a palindrome by comparing characters from both ends of the string towards the middle. In the main function, we test the word “radar” and find that it is indeed a palindrome.

Counting Vowels and Consonants

Let’s create a C function that counts the number of vowels and consonants in a given string.

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

int countVowelsConsonants(char str[], int *vowels, int *consonants) {
    *vowels = 0;
    *consonants = 0;
    int length = strlen(str);
    
    for (int i = 0; i < length; i++) {
        char c = tolower(str[i]); // Convert character to lowercase for easier comparison
        
        if (c >= 'a' && c <= 'z') {
            if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
                (*vowels)++;
            } else {
                (*consonants)++;
            }
        }
    }
    return 1;
}

int main() {
    char sentence[] = "Hello, World!";
    int vowels, consonants;
    
    countVowelsConsonants(sentence, &vowels, &consonants);
    
    printf("Vowels: %d\n", vowels);
    printf("Consonants: %d\n", consonants);
    
    return 0;
}

Output and Explanation:

Vowels: 3
Consonants: 7

In this example, we create the countVowelsConsonants function, which counts the number of vowels (a, e, i, o, u) and consonants in a given string, ignoring case and non-alphabetic characters. In the main function, we test it with the sentence “Hello, World!” and count 3 vowels and 7 consonants.

FAQs

Q1: What is a null-terminated string in C?

A null-terminated string is a sequence of characters followed by a null character ('\0') that marks the end of the string in memory.

Q2: How do I concatenate two strings in C?

You can use the strcat() function to concatenate two strings in C.

Q3: Is it necessary to manually allocate memory for strings in C?

Yes, in C, you need to manually allocate memory for strings to ensure sufficient space for characters and the null terminator.

Q4: What is the Caesar cipher, and how is it used for encryption?

The Caesar cipher is a simple encryption technique where each character in the plaintext is shifted by a fixed number of positions to create the ciphertext.

Q5: What are some common mistakes to avoid when working with strings in C?

Avoid buffer overflows by ensuring that you don’t write more data into an array than its allocated size. Also, remember to null-terminate strings to prevent unexpected behavior.