Lesson 43 of 60 – Strings in C
72%

Strings in C

A string in C is a sequence of characters stored in a character array. C does not have a separate built-in string data type. Strings are represented using arrays of char and are terminated by a special null character '\0'.

Note: A C string must end with the null character '\0'. This character tells C where the string ends.

1. What is a String?

A string is a sequence of characters such as a name, city, message, or sentence.

"Hello"
"India"
"Welcome to C"

In C, strings are stored inside character arrays.

2. Character vs String

A character represents a single character, while a string represents a sequence of characters.

char ch = 'A';

char name[] = "Amit";

Single quotes are commonly used for character constants, while double quotes are used for string literals.

3. Declaring a String

A string can be declared using a character array.

char name[20];

This creates a character array capable of storing characters, including the terminating null character, within its declared size.

4. Initializing a String

A string can be initialized directly when declaring the character array.

char name[] = "Rahul";

The compiler automatically reserves space for the characters and the terminating '\0'.

5. Null Character

The null character '\0' marks the end of a C string.

char name[] = {'H', 'i', '\0'};

Functions that work with C strings use this character to determine where the string ends.

6. String and Array Indexes

Each character in a string is stored at an array index.

char name[] = "Hello";

printf("%c", name[0]);
printf("%c", name[1]);

The first character is stored at index 0.

7. Accessing Characters

Individual characters can be accessed using their indexes.

char word[] = "Computer";

printf("%c", word[0]);
printf("%c", word[3]);

The index must be within the valid bounds of the character array.

8. Changing a Character

Characters in a modifiable character array can be changed using an index.

char word[] = "Cat";

word[0] = 'B';

printf("%s", word);

The output becomes Bat.

9. Printing a String

The %s format specifier is commonly used with printf() to print a C string.

char name[] = "Amit";

printf("%s", name);

The characters are printed until the null character is reached.

10. Printing with a Message

A string can be printed together with other text.

char name[] = "Ravi";

printf("My name is %s", name);

This is useful for displaying formatted messages.

11. Taking String Input with scanf()

The %s format specifier can be used with scanf() to read a word.

char name[30];

scanf("%29s", name);

The array name is passed without & because it already represents the address of its first element in this context.

12. Limitation of scanf("%s")

When scanf("%s", ...) is used, input stops at whitespace.

char name[30];

scanf("%29s", name);

If the user enters Raj Kumar, only Raj is read. Use a line-input method when you need to read spaces.

13. Reading a Full Line with fgets()

The fgets() function can read a line of text, including spaces.

char name[50];

fgets(name, sizeof(name), stdin);

It is generally safer than using an unbounded scanf("%s", ...) for a character array.

14. fgets() and Newline

When the input fits in the buffer, fgets() may store the newline character entered by the user.

char name[50];

fgets(name, sizeof(name), stdin);

The newline can be removed when required before further processing.

15. String Length

The strlen() function is used to find the length of a C string. It is declared in <string.h>.

#include <string.h>

char word[] = "Hello";

printf("%zu", strlen(word));

The length does not include the terminating '\0'.

16. Copying Strings

The strcpy() function can copy a string into another character array.

#include <string.h>

char source[] = "Hello";
char destination[20];

strcpy(destination, source);

printf("%s", destination);

The destination array must have enough space for the copied string and its terminating null character.

17. Comparing Strings

The strcmp() function can be used to compare two strings.

#include <string.h>

char a[] = "Apple";
char b[] = "Apple";

if(strcmp(a, b) == 0)
{
    printf("Strings are equal");
}

18. Joining Strings

The strcat() function appends one string to another.

#include <string.h>

char first[30] = "Hello ";
char second[] = "World";

strcat(first, second);

printf("%s", first);

The destination array must have enough space for the resulting string.

19. String Header File

Many standard string functions are declared in:

#include <string.h>

Common functions include:

  • strlen()
  • strcpy()
  • strcat()
  • strcmp()

20. String Traversal

A string can be processed character by character using a loop.

char word[] = "Hello";

for(int i = 0; word[i] != '\0'; i++)
{
    printf("%c\n", word[i]);
}

The loop stops when it reaches the null character.

21. Counting Characters

A loop can be used to count characters in a string.

char word[] = "Computer";
int count = 0;

for(int i = 0; word[i] != '\0'; i++)
{
    count++;
}

printf("Length = %d", count);

22. Counting Vowels

You can check each character and count vowels.

char word[] = "education";
int count = 0;

for(int i = 0; word[i] != '\0'; i++)
{
    if(word[i] == 'a' || word[i] == 'e' ||
       word[i] == 'i' || word[i] == 'o' ||
       word[i] == 'u')
    {
        count++;
    }
}

printf("Vowels = %d", count);

23. Converting a Character

Characters can be changed individually. For example, a lowercase letter can be changed to uppercase using the appropriate character conversion function.

#include <ctype.h>

char ch = 'a';

printf("%c", toupper((unsigned char)ch));

The <ctype.h> header provides functions such as toupper() and tolower().

24. String Literals and Character Arrays

A string literal can initialize a character array.

char city[] = "Patna";

The array contains the characters of the string followed by a null character. The array contents can be modified.

city[0] = 'R';

25. String Literal vs Character Array

It is important to understand the difference between a character array and a string literal.

char name[] = "Amit";

Here, name is a modifiable character array initialized from the string literal.

Do not attempt to modify a string literal through a pointer.

const char *text = "Hello";

26. Common String Mistake: Small Array

Always provide enough space for the characters and the terminating '\0'.

char name[6] = "Hello";

This is valid because five characters plus the null character require six elements.

An array that is too small cannot safely hold the complete string.

27. Common String Mistake: Using ==

Do not use == to compare the contents of two C strings.

strcmp(first, second) == 0

The strcmp() function compares the characters of the strings.

28. Complete String Program

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

int main()
{
    char name[50];

    printf("Enter your name: ");
    fgets(name, sizeof(name), stdin);

    printf("Name: %s", name);
    printf("Length: %zu", strlen(name));

    return 0;
}

This program reads a line of text and finds its length. If the input fits in the array, fgets() may also store the newline.

29. Practical Uses of Strings

Strings are used in many real-world programs.

  • Student names
  • Usernames
  • Passwords and login input
  • Addresses
  • Messages
  • City and country names
  • File names
  • Search text
  • Descriptions
  • Text processing

30. Practice Program

Create a C program that:

  1. Takes a student's name as input.
  2. Displays the name.
  3. Finds its length.
  4. Counts the vowels.
  5. Counts the consonants.
  6. Displays each character on a separate line.

Use a character array, loops, and appropriate string/character functions.

📌 Key Points

  • C strings are stored in character arrays.
  • A C string ends with the null character '\0'.
  • The first character is at index 0.
  • %s is commonly used to print a string.
  • scanf("%s", ...) reads a word and stops at whitespace.
  • fgets() can be used to read a line containing spaces.
  • strlen() finds string length.
  • strcpy() copies a string.
  • strcat() appends one string to another.
  • strcmp() compares string contents.
  • String functions are commonly declared in <string.h>.
  • Always allocate enough space for the string and its null character.

🧠 Quick Quiz

Question: Which character marks the end of a C string?