# 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:

```c
char str[size];
```

#### 2.2 Initialization Methods

1. **Using a String Literal**:

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

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

   ```c
   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`**:

   ```c
   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):

   ```c
   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:

```c
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**:

```c
#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**:

```c
#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**:

```c
#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**:

```c
#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**:

```c
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**:

```c
#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**:

```c
#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**:

```c
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**:

```c
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**:

```c
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**:

```c
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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cs.d19.in/c-programming/basics/arrays/strings-char-arrays.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
