learnprogramming123

LEARN PROGRAMMING 123
your resources to programming and free tutition



Navigation

 
C
 
C++ soon here!
VB - soon here!

Search

 

 

 

 

Next Back


Lesson 10: Strings

This lesson will show you how to:

  • what are strings?
  • assigning strings to variables
  • use of the strcpy() function
  • use of the string.h header file

Q: Why didn't the blonde want a window seat on the plane?
A: She'd just blow dried her hair and she didn't want it blown around too much.

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 using thedata type "char". String data is stored as a null character terminated character array.

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(void)
{

    char sentence[] = "Hello World";
    int count = 0, 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. You can use this technique to search for any chracter in any string.

Library Functions for String Manipulation


To use any of these functions in your code, the header file "strings.h" must be included. It is the programmer's responsibility to check that the destination array is large enough to hold either what is copied or appended to it. C performs no error checking in this respect.

strcpy()
strcpy copies a string, including the null character terminator from the source string to the destination. You must attach the string.h header file to use this function. This is the only function from that library that i want you to know for now, the remaining functions in that library are not that important nor useful. Its prototype is:

strcpy(variable, "string");

ariable is the variable (now known as a string literal) that the string will be assigned to, string is the actual string that you are assigning to the variable.

Example:

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

int main(void)
{

    const char yes = ‘y’

    char reply;
    char garment[] = “overcoat”;

    printf(“Is it raining outside? Answer y/n \n”);

    scanf(“%c”, &reply);

    if (reply == yes)
        strcpy (garment, “raincoat”);

    printf(“before you go out today take your %s\n”, garment);

    return 0;

}

back to top        go to next lesson

 

 






1