C guide
  • Hello reader!
  • C programming
    • C
    • Roadmap
    • Basics
      • Variables in C
      • I/O in C
      • Data types
      • Operators
      • Control Flow
      • Arrays
        • Strings (char arrays)
        • Multidimensional Arrays
    • Functions!
      • Recursion
  • Pointers
    • Pointer-Array Relationship
  • Structures and Unions
  • Dynamic memory allocation
  • File I/O (Input/Output)
  • Advanced topics
  • Debugging & Optimization
  • Practices
  • Cheatsheet
Powered by GitBook
On this page
  • Chapter: Strings in C
  • 1. What is a String?
  • 2. Declaring and Initializing Strings
  • 3. Input and Output of Strings
  • 4. String Operations
  • 5. Iterating Over Strings
  • 6. Common String Problems
  • 7. Best Practices for Handling Strings
  • Summary

Was this helpful?

  1. C programming
  2. Basics
  3. Arrays

Strings (char arrays)

Chapter: Strings in C


Strings are a fundamental concept in programming, representing sequences of characters. In C, strings are implemented as arrays of characters, terminated by a special null character (\0). This chapter delves into all aspects of strings in C, including their declaration, initialization, operations, and common problems, with clear examples.


1. What is a String?

In C, a string is a collection of characters stored in a character array, with the null character (\0) indicating the end of the string. This null character is crucial for distinguishing strings from plain arrays of characters.

Example:

A string "Hello" is stored as:

'H'  'e'  'l'  'l'  'o'  '\0'

Key Points:

  1. Strings are null-terminated.

  2. The null character (\0) must always be included, either explicitly or implicitly.

  3. Strings are immutable when defined as string literals.


2. Declaring and Initializing Strings

Strings can be declared in various ways:

2.1 Declaration

A string is declared as a character array:

char str[size];

2.2 Initialization Methods

  1. Using a String Literal:

    char str[] = "Hello";
  2. Explicit Character Array:

    char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
  3. Uninitialized Array: Declare an array and assign characters later:

    char str[10];
    str[0] = 'H';
    str[1] = 'i';
    str[2] = '\0';  // Ensure null termination

3. Input and Output of Strings

3.1 Reading Strings

Strings can be read using functions like scanf and fgets.

  1. Using scanf:

    char str[50];
    scanf("%s", str);  // Stops reading at spaces or newline

    Warning: scanf does not handle spaces in strings.

  2. Using fgets (Preferred for safety):

    char str[50];
    fgets(str, sizeof(str), stdin);  // Reads spaces and stops at newline

3.2 Printing Strings

Use printf with %s for string output:

char str[] = "Hello, World!";
printf("%s\n", str);

4. String Operations

C provides standard library functions in <string.h> for common string manipulations.


4.1 Find the Length of a String

Function: strlen

The strlen function computes the length of a string (excluding the null character).

Example:

#include <string.h>
char str[] = "Hello";
int length = strlen(str);  // length = 5

4.2 Copy a String

Function: strcpy

The strcpy function copies a source string into a destination string.

Example:

#include <string.h>
char source[] = "Hello";
char destination[10];
strcpy(destination, source);

4.3 Concatenate Strings

Function: strcat

The strcat function appends one string to the end of another.

Example:

#include <string.h>
char str1[20] = "Hello";
char str2[] = " World";
strcat(str1, str2);  // str1 becomes "Hello World"

4.4 Compare Strings

Function: strcmp

The strcmp function compares two strings lexicographically:

  • Returns 0 if equal.

  • Returns a positive value if the first string is greater.

  • Returns a negative value if the first string is smaller.

Example:

#include <string.h>
char str1[] = "Apple";
char str2[] = "Banana";
int result = strcmp(str1, str2);  // result < 0

4.5 Reverse a String

C does not have a standard strrev function. You can reverse a string manually:

Manual Example:

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

4.6 Search for a Substring

Function: strstr

The strstr function finds the first occurrence of a substring in a string.

Example:

#include <string.h>
char str[] = "Hello, World!";
char *substring = strstr(str, "World");  // substring points to "World!"

4.7 Tokenize a String

Function: strtok

The strtok function splits a string into tokens based on a delimiter.

Example:

#include <string.h>
char str[] = "Hello,World,!";
char *token = strtok(str, ",");
while (token != NULL) {
    token = strtok(NULL, ",");
}

5. Iterating Over Strings

Strings can be treated as arrays, allowing character-by-character traversal.

Example:

char str[] = "Hello";
for (int i = 0; str[i] != '\0'; i++) {
    // Process str[i]
}

6. Common String Problems

Problem 1: Palindrome Check

A palindrome reads the same backward as forward.

Solution:

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

Problem 2: Count Vowels and Consonants

Solution:

void countVowelsConsonants(char str[], int *vowels, int *consonants) {
    *vowels = *consonants = 0;
    for (int i = 0; str[i] != '\0'; i++) {
        char ch = tolower(str[i]);
        if (ch >= 'a' && ch <= 'z') {
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                (*vowels)++;
            } else {
                (*consonants)++;
            }
        }
    }
}

Problem 3: Count Character Occurrences

Solution:

int countOccurrences(char str[], char ch) {
    int count = 0;
    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] == ch) {
            count++;
        }
    }
    return count;
}

7. Best Practices for Handling Strings

  1. Always Null-Terminate: Ensure strings are properly terminated with \0.

  2. Use Safe Input Functions: Prefer fgets over gets to prevent buffer overflows.

  3. Avoid Modifying String Literals: Modifying a string literal causes undefined behavior.

  4. Allocate Sufficient Memory: Ensure arrays are large enough to store the string and the null character.


Summary

In this chapter, we explored strings in C, covering their structure, initialization, and essential operations like concatenation, comparison, and tokenization. With this foundation, you can efficiently work with strings to solve real-world text-processing problems. Remember to practice with the provided examples to strengthen your skills.

PreviousArraysNextMultidimensional Arrays

Last updated 6 months ago

Was this helpful?