String

String

String in C

Written by: hossain1907056

Wed, 20 Nov 2024

Strings in C

In C, strings are an essential way to work with text. Unlike other programming languages, C doesn’t have a dedicated string type. Instead, strings are handled as arrays of characters with a special terminator.

What is a String in C?

In C, a string is essentially an array of characters terminated by a null character ('\0'). This null character indicates the end of the string, so functions in C know where to stop reading the string. For example, the string "Hello" is represented in C as a character array with six elements:

char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

Or simply:

char str[] = "Hello";

Declaring Strings in C

There are two main ways to declare strings in C:

As an array of characters :
char str[20];

Here, str can hold up to 19 characters, with the 20th reserved for the null terminator ('\0').

Direct Initialization :
char str[] = "Hello, World!";

In this case, the compiler automatically calculates the required size based on the initial value, including the null terminator. Example:

#include <stdio.h>
int main() {
    char name[] = "Alice"; // string literal
    printf("Name: %s\n", name);
    return 0;
}
String Input and Output

To read strings from the user, you can use the scanf() or gets() functions (although gets() is unsafe and fgets() is preferred). To print strings, use printf().

#include <stdio.h>
int main() {
    char name[50];
    printf("Enter your name: ");
    scanf("%s", name); // reads until whitespace
    printf("Hello, %s!\n", name);
    return 0;
}

Note: scanf() stops reading at whitespace. If you want to read a full line, use fgets().

fgets(name, sizeof(name), stdin); // reads until newline or buffer limit

Common String Operations

C provides several functions for common string operations in the string.h library.

String Length: strlen()

Finds the length of a string (number of characters before '\0').

#include <stdio.h>
#include <string.h>
int main() {
    char str[] = "Hello";
    printf("Length of str: %lu\n", strlen(str));
    return 0;
}
String Copy: strcpy()

Copies one string to another.

char str1[20], str2[] = "Hello";
strcpy(str1,str2);
String Concatenation: strcat()

Appends one string to the end of another.

char str1[20] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2);
String Comparison: strcmp()

Compares two strings lexicographically. Returns

  • 0 if equal,
  • < 0 if str1 < str2
  • > 0 if str1 > str2
if (strcmp(str1, str2) == 0) {
    printf("Strings are equal\n");
}
String Search: strstr()

Searches for a substring within a string.

char str[] = "Hello, World!";
char *pos = strstr(str, "World");
    if (pos) {
        printf("Found substring at position: %ld\n", pos - str);
    }

String Manipulation Examples

Let’s explore some common use cases and examples for manipulating strings.

Example 1: Converting a String to Uppercase

To convert all characters in a string to uppercase, loop through each character and use toupper() (from ctype.h).

#include <stdio.h>
#include <ctype.h>
int main() {
    char str[] = "Hello, World!";
    for (int i = 0; str[i] != '\0'; i++) {
        str[i] = toupper(str[i]);
    }
    printf("Uppercase: %s\n", str);
    return 0;
}
Example 2: Reversing a String

Reversing a string requires swapping characters from the start and end until reaching the middle.

#include <stdio.h>
#include <string.h>
void reverse(char str[]) {
    int len = strlen(str);
    for (int i = 0; i < len / 2; i++){
        char temp = str[i];
        str[i] = str[len - i - 1];
        str[len - i - 1] = temp;
    }
}
int main() {
    char str[] = "Hello";
    reverse(str);
    printf("Reversed string: %s\n", str);
    return 0;
}
Example 3: Checking if a String is a Palindrome

A palindrome reads the same backward and forward.

#include <stdio.h>
#include <string.h>
int isPalindrome(char str[]) {
    int len = strlen(str);
    for (int i = 0; i < len / 2; i++) {
        if (str[i] != str[len - i - 1]) {
            return 0; // Not a palindrome
        }
    }
    return 1; // Palindrome
}
int main() {
    char str[] = "madam";
    if (isPalindrome(str)) {
        printf("%s is a palindrome\n", str);
    } 
    else {
        printf("%s is not a palindrome\n", str);
    }
    return 0;
}
User12024-11-02

This is a comment 1.

User12024-11-02

This is a comment 2.