Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development

  • Print
  • + Share This
This chapter is from the book

Accessing the String's Characters

We learned earlier that you can think of a string as an array of characters. In Chapter 9, "Arrays and Collections," you will learn how to allocate arrays and navigate through arrays. In this chapter you will get a little preview of navigating through character arrays.

To access the characters of a string:

  • Type char c = str[x]; where c is a variable to hold the character from the string, str is the string variable and x is the zero-based position of the character you wish to save (Figure 4.40).

    Figure 4.40Figure 4.40 Because strings are essentially arrays of characters, you can address any character in the array by specifying its zero-based index in square brackets.

Tips

  • There are two ways of enumerating through all the characters in a string. One way is to write a loop where you maintain an index with an integer variable. The index begins at zero and increases until the index is equal to Length –1 (see "Finding the String's Length" earlier in this chapter) (Figure 4.41). The other way is to use a function called foreach, which will be explained in detail in Chapter 9, "Arrays and Collections" (Figure 4.42).

    Figure 4.41Figure 4.41 This code shows a common way to parse the characters of the string in a loop. It searches for commas to count names.

    Figure 4.42Figure 4.42 An easier way to navigate through the characters of the string is to use the foreach method.

  • If you ask for an index greater than Length –1, the string class generates an exception (see Chapter 10, "Exceptions," for details). The exception (or error) is IndexOutOfBoundsException.

  • You can access the characters of the string, but you can't modify them since strings are immutable (Figure 4.43).

    Figure 4.43Figure 4.43 You can reassign a string variable to another string but you can't really change an existing string.

  • If the IndexOf or LastIndexOf functions don't find any occurrences of the substring, the functions return –1.

  • There are a few variations of the IndexOf and LastIndexOf functions. One variation lets you specify a location within the string where you want to start the search. This is useful for cases in which you wish to scan the string for one character, then when you find it, you want to get the next occurrence of the same character. In that case you specify that you want to begin the search in the position after the first occurrence (Figure 4.45).

    Figure 4.45Figure 4.45 Without specifying an index, IndexOf always searches from the same character. However, you can specify a starting position, as you can see from the examples above.

  • + Share This
  • 🔖 Save To Your Account