11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 7: Storing Sequences in Arrays 103The choice of ‘\0’ as the terminating character was not random. Rememberthat zero is the only numeric value that converts to false; all other valuestranslate to true. This means that the for loop could (and usually is) writtenas:for(int i = 0; stringArray[i]; i++)This whole business of null terminated character strings is so ingrained intothe C++ language psyche that C++ uses a string of characters surrounded bydouble quotes to be an array of characters automatically terminated with a‘\0’ character. The following are identical declarations:char szMyName[] = “Stephen”;char szAlsoMyName[] ={‘S’, ‘t’, ‘e’, ‘p’, ‘h’, ‘e’, ‘n’, ‘\0’};The naming convention used here is exactly that, a convention. C++ does notcare. The prefix sz stands for zero-terminated string.The string Stephen is eight characters long and not seven — the null characterafter the n is assumed. The string “” is one character long consisting ofjust the null character.Manipulating Strings with CharacterThe C++ programmer is often required to manipulate strings. C++ provides anumber of standard string-manipulation functions to make the job easier. Afew of these functions are listed in Table 7-1.Table 7-1Nameint strlen(string)void strcpy(target, source, n)void strcat(target, source, n)void strncpy(target, source, n)String-Handling FunctionsOperationReturns the number of charactersin a string.Copies the source string into atarget array.Concatenates the source stringonto the end of the target string.Copies a string up to n charactersfrom the source string into a targetarray.(continued)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!