Introduction to Programming

Strings


"String" is just a fancy way of saying "text" or "a bunch of characters." It's the word programmers use, though, so we'll use "string." A string in C is stored as an array of characters. From the earlier array example, you can guess how to define an array of characters:
char my_string[20];
my_string[0] = 'H';
my_string[1] = 'e';
my_string[2] = 'l';
my_string[3] = 'l';
my_string[4] = 'o';
my_string[5] = 0;
printf("The value of my_string is %s\n", my_string);
I want you to notice two things here. First, I'm using the %s format code. This is a special code just for strings. It expects a character-array to be the next argument to printf. It then steps through the array one character at a time, adding each character to the screen. Secondly, I set element 5 of my_string to 0, not '0'. What's the difference? '0' would put an actual zero on the screen. I don't want "Hello0", so I didn't use '0'. The raw zero, without the single-quotes '' tells the computer "this is the end of the string." Without that, %s would keep putting up characters onto the screen until it crashed or found another raw zero somewhere.

String Functions

There are a number of helper functions for strings. You can use these so you don't end up having to do what I did above, setting each character one at a time.

fgets

fgets gets a string from the user. You may remember this from earlier examples.
char user_input[128];
fgets(user_input, 127, stdin);

strcpy

strcpy copies one string to another.
char my_string[128];
strcpy(my_string, "Copy from this string!");

strcmp

Compares one string to another. 0 means they are equal, any other result means they are different.
char user_input[128];
fgets(user_input, 127, stdin);
if (strcmp(user_input, "hello\n") == 0)
    printf("You said hello to me! :)\n");
else
    printf("Why didn't you say hello to me?! :(\n");


Challenges

  1. Try getting a string from the user and print out the third character in the string. Hint: What's the format code for a single character? Hint #2: How does the fact that computers start counting with zero (instead of one) change the way you're going to select the "third" element?
  2. Try expanding the "You said hello" example above to make a simple conversation between the computer and the user.


Next: Functions

Previous: Arrays


Introduction to Programming

Home