Chapter 9: Character Arrays and Strings

📌 Learning Objectives
  • LO 9.1: Declare and initialize string variables
  • LO 9.2: Read and write strings from/to terminal
  • LO 9.3: Perform arithmetic operations on characters
  • LO 9.4: Use string handling functions
  • LO 9.5: Work with tables of strings

9.1 Introduction to Strings

A string is a sequence of characters that is treated as a single data item. In C, strings are represented as character arrays terminated by a null character '\0'.

String constant example:

"Man is obviously made to think."

To include double quotes within a string, use escape sequence:

"\"Man is obviously made to think,\" said Pascal."
💡 Note: C does not support strings as a built-in data type. They are implemented as arrays of characters.

9.2 Declaring and Initializing String Variables

String variables are declared as character arrays:

char city[10];
char name[30];

Important: The array size must be one more than the maximum number of characters to accommodate the null terminator '\0'.

Initialization Methods

// Method 1: String constant
char city[9] = "NEW YORK";

// Method 2: Character array
char city[9] = {'N','E','W',' ','Y','O','R','K','\0'};

// Method 3: Without size (size determined automatically)
char string[] = {'G','O','O','D','\0'};  // 5 elements
char name[] = "John";  // 5 elements (including '\0')

// Method 4: Larger array than string
char str[10] = "GOOD";  // str[4] = 'D', str[5] = '\0', rest are NULL
Memory representation of char str[10] = "GOOD";

Index:   0     1     2     3     4     5     6     7     8     9
      +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
      | 'G' | 'O' | 'O' | 'D' | '\0'|     |     |     |     |     |
      +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
⚠️ Important: The following are illegal:
char str3[5];
str3 = "GOOD";  // Cannot assign to array after declaration

char s2[4];
s2 = s1;  // Cannot assign one array to another

9.3 Reading Strings from Terminal

Using scanf() with %s

char address[10];
scanf("%s", address);  // Note: no & operator for strings

Problem: scanf() with %s stops reading at the first whitespace.

Input: "NEW YORK"
Result: address contains "NEW" only

Reading with Field Width

char name[10];
scanf("%5s", name);  // Reads only 5 characters

Reading a Line with Spaces using %[^\n]

char line[80];
scanf("%[^\n]", line);  // Reads until newline

Using getchar()

We can read a line character by character:

📝 Worked-Out Problem 9.1

Reading a line using getchar():

#include <stdio.h>

int main() {
    char line[80];
    int c = 0;
    char ch;
    
    printf("Enter a line of text:\n");
    ch = getchar();
    
    while (ch != '\n' && c < 79) {
        line[c] = ch;
        c++;
        ch = getchar();
    }
    line[c] = '\0';  // terminate the string
    
    printf("You entered: %s\n", line);
    
    return 0;
}
Output:
Enter a line of text:
Hello World! This is C programming.
You entered: Hello World! This is C programming.

Using gets()

The gets() function reads a line including spaces until newline is encountered.

char line[80];
gets(line);  // Reads a line of text
puts(line);  // Prints the line and moves to next line
⚠️ Security Note: gets() does not check array bounds and can cause buffer overflow. In modern C, use fgets() instead.

9.4 Writing Strings to Screen

Using printf() with %s

printf("%s", name);  // Prints entire string
printf("%10s", name);  // Prints in field width 10, right-justified
printf("%-10s", name); // Left-justified
printf("%10.4s", name); // Prints first 4 chars in width 10

📝 Worked-Out Problem 9.2

Various string output formats:

#include <stdio.h>

int main() {
    char str[] = "HELLO";
    
    printf("1. %s\n", str);
    printf("2. %10s\n", str);
    printf("3. %-10sEND\n", str);
    printf("4. %3s\n", str);  // width less than string length
    printf("5. %.3s\n", str);
    printf("6. %10.3s\n", str);
    printf("7. %-10.3sEND\n", str);
    
    return 0;
}
Output:
1. HELLO
2. HELLO
3. HELLO END
4. HELLO
5. HEL
6. HEL
7. HEL END

Using puts()

puts(str);  // Prints string and automatically adds newline

9.5 Arithmetic Operations on Characters

Characters in C are represented by their ASCII values and can be used in arithmetic expressions.

char ch = 'a';
printf("%d\n", ch);  // Prints 97 (ASCII value)

char digit = '7';
int value = digit - '0';  // Converts character to integer (7)

📝 Worked-Out Problem 9.3

Printing alphabet set in decimal and character form:

#include <stdio.h>

int main() {
    char c;
    
    printf("ASCII values of uppercase letters:\n");
    for (c = 'A'; c <= 'Z'; c++) {
        printf("%c = %d\t", c, c);
        if ((c - 'A' + 1) % 5 == 0)
            printf("\n");
    }
    
    printf("\n\nASCII values of lowercase letters:\n");
    for (c = 'a'; c <= 'z'; c++) {
        printf("%c = %d\t", c, c);
        if ((c - 'a' + 1) % 5 == 0)
            printf("\n");
    }
    
    return 0;
}
Partial Output:
ASCII values of uppercase letters:
A = 65 B = 66 C = 67 D = 68 E = 69
F = 70 G = 71 H = 72 I = 73 J = 74
...

9.6 String Handling Functions

C library provides several string handling functions in <string.h>.

Function Purpose Example
strlen(s) Returns length of string s (excluding '\0') int len = strlen("Hello"); // len = 5
strcpy(s1, s2) Copies s2 into s1 strcpy(city, "DELHI");
strncpy(s1, s2, n) Copies first n characters of s2 into s1 strncpy(city, "DELHI", 3);
strcat(s1, s2) Concatenates s2 to the end of s1 strcat(greeting, "World");
strncat(s1, s2, n) Concatenates first n chars of s2 to s1 strncat(greeting, "World", 3);
strcmp(s1, s2) Compares s1 and s2 (returns 0 if equal) if (strcmp(str1, str2) == 0)
strncmp(s1, s2, n) Compares first n characters if (strncmp(str1, str2, 3) == 0)
strstr(s1, s2) Finds first occurrence of s2 in s1 char *p = strstr(text, "world");
strchr(s, c) Finds first occurrence of character c in s char *p = strchr(text, 'o');
strrchr(s, c) Finds last occurrence of character c in s char *p = strrchr(text, 'o');

📝 Worked-Out Problem 9.4

Illustration of string handling functions:

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

int main() {
    char s1[20] = "Hello";
    char s2[20] = "World";
    char s3[40];
    int len, cmp;
    
    printf("s1 = %s, length = %lu\n", s1, strlen(s1));
    printf("s2 = %s, length = %lu\n", s2, strlen(s2));
    
    cmp = strcmp(s1, s2);
    printf("strcmp(s1, s2) = %d\n", cmp);
    
    strcpy(s3, s1);
    printf("strcpy(s3, s1): s3 = %s\n", s3);
    
    strcat(s3, s2);
    printf("strcat(s3, s2): s3 = %s\n", s3);
    
    printf("Length of s3 = %lu\n", strlen(s3));
    
    return 0;
}
Output:
s1 = Hello, length = 5
s2 = World, length = 5
strcmp(s1, s2) = -15 (or negative)
strcpy(s3, s1): s3 = Hello
strcat(s3, s2): s3 = HelloWorld
Length of s3 = 10

📝 Worked-Out Problem 9.5

Program to check if a string is palindrome:

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

int main() {
    char str[100];
    int i, j, flag = 1;
    
    printf("Enter a string: ");
    gets(str);
    
    j = strlen(str) - 1;
    for (i = 0; i < j; i++, j--) {
        if (str[i] != str[j]) {
            flag = 0;
            break;
        }
    }
    
    if (flag)
        printf("%s is a palindrome\n", str);
    else
        printf("%s is not a palindrome\n", str);
    
    return 0;
}
Output:
Enter a string: madam
madam is a palindrome

Enter a string: hello
hello is not a palindrome

9.7 Table of Strings (Two-Dimensional Character Arrays)

We can store a list of strings using a two-dimensional character array.

char cities[5][15] = {
    "Chandigarh",
    "Madras",
    "Delhi",
    "Bombay",
    "Calcutta"
};
Memory representation:

cities[0] → C h a n d i g a r h \0
cities[1] → M a d r a s \0
cities[2] → D e l h i \0
cities[3] → B o m b a y \0
cities[4] → C a l c u t t a \0

📝 Worked-Out Problem 9.6

Sorting strings in alphabetical order:

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

int main() {
    char names[5][20], temp[20];
    int i, j;
    
    printf("Enter 5 names:\n");
    for (i = 0; i < 5; i++) {
        printf("Name %d: ", i+1);
        gets(names[i]);
    }
    
    // Bubble sort for strings
    for (i = 0; i < 4; i++) {
        for (j = 0; j < 4 - i; j++) {
            if (strcmp(names[j], names[j+1]) > 0) {
                strcpy(temp, names[j]);
                strcpy(names[j], names[j+1]);
                strcpy(names[j+1], temp);
            }
        }
    }
    
    printf("\nSorted names:\n");
    for (i = 0; i < 5; i++)
        printf("%s\n", names[i]);
    
    return 0;
}
Output:
Enter 5 names:
Name 1: John
Name 2: Alice
Name 3: Bob
Name 4: David
Name 5: Charlie

Sorted names:
Alice
Bob
Charlie
David
John

9.8 Array of Pointers to Strings

Instead of two-dimensional arrays, we can use an array of pointers to strings, which is more memory-efficient.

char *names[5] = {
    "Chandigarh",
    "Madras",
    "Delhi",
    "Bombay",
    "Calcutta"
};

This creates a "ragged array" where each string occupies only the space it needs.

9.9 Other String Functions

atoi() - String to Integer

#include <stdlib.h>
char num_str[] = "1988";
int year = atoi(num_str);  // year = 1988

String Conversion Functions

FunctionDescription
atoi(s)Converts string to int
atol(s)Converts string to long
atof(s)Converts string to float/double
itoa(n, s, base)Converts integer to string (not standard)

Important Points to Remember

  • Character constants are enclosed in single quotes; string constants in double quotes.
  • Allocate sufficient space for the null character at the end.
  • Do not use & with string variables in scanf().
  • Strings cannot be manipulated with operators; use string functions.
  • Include <string.h> for string functions.
  • Include <ctype.h> for character functions.
  • Include <stdlib.h> for conversion functions.

Chapter Exercises

Review Questions

  1. State true or false:
    a) When initializing a string variable during declaration, we must include the null character as part of the string constant.
    b) The gets() function automatically appends the null character at the end of the string.
    c) When reading a string with scanf(), it automatically inserts the terminating null character.
    d) The function scanf() cannot be used to read a line of text with whitespaces.
    e) String variables cannot be used with the assignment operator.
  2. Describe the limitations of using getchar() and scanf() for reading strings.
  3. Assuming the variable string contains "The sky is the limit.", determine the output of:
    a) printf("%s", string);
    b) printf("%15s", string);
    c) printf("%.10s", string);
  4. Compare the working of strcpy() and strncpy().

Multiple Choice Questions

  1. Which of the following values can be returned by strcmp()?
    a) Positive value
    b) Negative value
    c) Zero
    d) All of these
  2. Which function is used to search a substring in another string?
    a) searchstr()
    b) strstr()
    c) substr()
    d) None
  3. Which array can store the names of 10 employees?
    a) employee[10][80]
    b) employee[80][10]
    c) employee[][10][80]
    d) None
  4. A character array str[] stores "Hello". What will strlen(str) return?
    a) 5
    b) 6
    c) 0
    d) None

Debugging Exercises

Find errors in the following code segments:

char str[10];
strncpy(str, "GOD", 3);
printf("%s", str);  // No null terminator!

char str[10];
strcpy(str, "Balagurusamy");  // String too long

if strstr("Balagurusamy", "guru") == 0)
    printf("Substring found");

char s1[5], s2[10];
gets(s1, s2);  // Wrong number of arguments

Programming Exercises

  1. Write a program that reads your name from the keyboard and outputs a list of ASCII codes for each character.
  2. Write a program to extract a portion of a character string. Assume m characters are extracted starting from the nth character.
  3. Write a program to count all occurrences of a particular word in a text.
  4. Write a program to replace a particular word by another word in a given string.
  5. Write a program to read a string and determine whether it is a palindrome (ignore case).
  6. Write a program to read the cost of an item in the form RRRR.PP and convert it to words (e.g., 125.75 → "ONE HUNDRED TWENTY FIVE AND PAISE SEVENTY FIVE").
  7. Write a program to read and store details of students (roll number, name, marks) and produce:
    a) Alphabetical list of names
    b) List sorted on roll numbers
    c) Rank-wise list sorted on marks
  8. Write a program to find the largest and smallest word in a string.
  9. Write a program to concatenate two strings without using strcat().

Interview Questions

  1. What will be the output of:
    printf("%d", printf("Hello"));
  2. What is the difference between char arr[] = "Hello" and char *ptr = "Hello"?
  3. Can you write a program that does not use any semicolon but executes successfully?
  4. What is the strstr() function used for?
  5. What will be the output of:
    char s1[] = "Jabalpur";
    char s2[] = "Jaipur";
    printf("%d", strncmp(s1, s2, 2));

Case Study 1: Counting Words in a Text

📝 Case Study: Counting Characters, Words, and Lines

#include <stdio.h>

int main() {
    char line[81];
    int char_count = 0, word_count = 0, line_count = 0;
    int in_word = 0;
    
    printf("Enter text (blank line to exit):\n");
    
    while (1) {
        gets(line);
        if (line[0] == '\0')
            break;
            
        line_count++;
        
        for (int i = 0; line[i] != '\0'; i++) {
            char_count++;
            
            if (line[i] == ' ') {
                in_word = 0;
            }
            else if (in_word == 0) {
                in_word = 1;
                word_count++;
            }
        }
        in_word = 0;
    }
    
    printf("\nStatistics:\n");
    printf("Characters: %d\n", char_count);
    printf("Words: %d\n", word_count);
    printf("Lines: %d\n", line_count);
    
    return 0;
}
Output:
Enter text (blank line to exit):
This is a sample text.
It has multiple lines.
And some words.

Statistics:
Characters: 45
Words: 9
Lines: 3

Case Study 2: Processing a Customer List

📝 Case Study: Alphabetizing a Customer List

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

int main() {
    char customers[5][50] = {
        "John R. Argand",
        "Peter J. Smith",
        "Alice M. Brown",
        "Robert K. Jones",
        "Mary L. Davis"
    };
    char last_name[5][20];
    char temp[50];
    int i, j;
    
    // Extract last names
    for (i = 0; i < 5; i++) {
        char *last = strrchr(customers[i], ' ');
        if (last != NULL)
            strcpy(last_name[i], last + 1);
        else
            strcpy(last_name[i], customers[i]);
    }
    
    // Sort by last name (bubble sort)
    for (i = 0; i < 4; i++) {
        for (j = 0; j < 4 - i; j++) {
            if (strcmp(last_name[j], last_name[j+1]) > 0) {
                // Swap last names
                strcpy(temp, last_name[j]);
                strcpy(last_name[j], last_name[j+1]);
                strcpy(last_name[j+1], temp);
                
                // Swap full names
                strcpy(temp, customers[j]);
                strcpy(customers[j], customers[j+1]);
                strcpy(customers[j+1], temp);
            }
        }
    }
    
    printf("Sorted by last name:\n");
    for (i = 0; i < 5; i++)
        printf("%s\n", customers[i]);
    
    return 0;
}