Chapter 7  - Strings and String Processing

Chapter Objectives

You should be able to:

  • Manipulate string data using string data structures and classes.
  • Solve problems that involve manipulating strings.
  • Use loops in designing string processing algorithms.
  • Demonstrate your understanding of how inheritance can be used in program design.

Index:

Introduction

Constructing Strings

String Conconcatenation

Indexing Strings

Converting Data to Strings and vice versa

Finding things within a String


/**
  * Pre:  s and keyword are any Strings
  * Post: keywordSearch() returns a String containing the
  *  number of occurrences of keyword in s, followed
  *  by the starting location of each occurrence
  */
public String keywordSearch(String s, String keyword) {
        String resultStr = "";
        int count = 0;
        int ptr = s.indexOf(keyword);
        while (ptr != -1) {
            ++count;
            resultStr = resultStr + ptr + " ";
            ptr = s.indexOf(keyword, ptr + 1);     // Find next occurrence
        }
        resultStr = count + ": " + resultStr;      // Insert the count
        return resultStr;                          // Return as a String
} // keywordSearch()

Miscellaneous String Methods

Method Signature  Example Value
boolean endsWith( String suffix) "Perfection".endsWith("tion")  true
boolean startsWith(String prefix) "Perfection".startsWith("Per")  true
String toUpperCase()   "Perfection".toUpperCase()  "PERFECTION"
String toLowerCase()   "Perfection".toLowerCase()  "perfection"
String trim() " Perfection ".trim()   "Perfection"

Comparing Strings

StringTokenizer


Summary


Key terms :  delimiter, equal strings, identical strings,lexicographic order,  string literal, token

Suggested Exercises :  1, 2, 3, 4, 5, 14, 16, 21