StringsAlt - Strings in C Basically, strings are character...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Strings in C Basically, strings are character arrays in C. However, that isn't the complete picture. It would be nice if strings didn't always have to be the same length, as character arrays are. In order to deal with this issue, strings in C, by default, are null terminated. This means that the last character storing a string is the null character, '\0'. For example, the following is a valid way to initialize a string to store "hello"; char word[20]; word[0] = 'h'; word[1] = 'e'; word[2] = 'l'; word[3] = 'l'; word[4] = 'o'; word[5] = '\0'; In this example, the character array word is storing a string of length 5. Notice that we actually store six characters here. This means that a character array of size 20 can actually store a string with a maximum length of 19, NOT 20, since the last character in the array must be reserved for the null character. Another way to read in a string is from the keyboard directly into a character array: scanf("%s", word); This reads in all the characters typed in until whitespace is read in and automatically adds the null character to the end of what is read in. One consequence of this idea is that the literals 'a' and "a" are different. The first is a single character, the second is stored in a character array of at least size two, where the last character is the null character.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Example of Processing a String The three following examples turn a string into its uppercase version, return the length of a string and reverse the contents of a string. void to_upper(char *word) { int index = 0; while (word[index] != '\0') { word[index] = toupper(word[index]); index++; } } int length(char *word) { int index=0; while (word[index] != '\0') index++; return index; } void reverse(char *word) {
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 06/09/2011 for the course COP 3223 taught by Professor Guha during the Spring '08 term at University of Central Florida.

Page1 / 8

StringsAlt - Strings in C Basically, strings are character...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online