www.easyCPlusPlus.com

Easy C++

www.easyCPlusPlus.com

C Tutorial - Lesson 10: Strings

Strings, Page 1

by John Kopp

Support this site at no cost to you

Welcome to easyCPlusPlus.com's C tutorial. This lesson covers the use of strings in C. It begins by presenting some basic ways to analyze and manipulate string data and then presents some C library functions that are useful for string manipulation. Character data is stored as the intrinsic data type char. String data is stored as a null character terminated character array. You may wish to review the lessons on input and output and arrays before studying this lesson.

Strings
Stings in C are stored as null character, '\0', terminated character arrays. This means that the length of a string is the number of characters it contains plus one to store the null character. Common string operations include finding lengths, copying, searching, replacing and counting the occurrences of specific characters and words. Here is a simple way to determine the length of a string.

#include <stdio.h>

int main()
{
    char sentence[] = "Hello World";
    int count = 0;
    int i;

    for (i = 0; sentence[i] != '\0'; i++)
    {
        count++;
    }
    printf("The string %s has %d characters ",
        sentence,count);
    printf("and is stored in %d bytes\n",
        count+1);

    return 0;
}

Each character within the array sentence is compared with the null character terminator until the end of the string is encountered. This technique can be generalized to search for any character.

Previous Page       Next Page