Miscellaneous string operations

The problem

Write a class with the following static methods:

  • wordCount. This method should accept a reference to a String object as an argument and return the number of words contained in the String.
  • mostFrequent. This method accepts a reference to a String object as an argument and returns the character that occurs the most frequently in the object.
  • replace sub string. This method accepts three references to String objects as arguments. Let's call them string1, string2, and string3. It searches string1 for all occurrences of string2. When it finds an occurrence of string2, it replaces it with string3. For example, suppose the three arguments have the following values that would return a reference to a String object with the value "that dog jumped over that fence":
    • string1: "the dog jumped over the fence"
    • string2: "the"
    • string3: "that"
  • arrayToString Convert array to string

Demonstrate each of these methods in a complete program.

Breaking it down

Word count

StringTokenizer uses the space character, the tab character, the newline character, the carriage-return character, and the form-feed character (" \t\n\r\f") as a set of predefined delimiters to split a string. countTokens() will return the number of tokens remaining in the current delimiter set which results in the number of words in a string. One thing to note is that the delimiters themselves will not be treated as tokens.

public static int wordCount(String phrase) {
    StringTokenizer strTok = new StringTokenizer(phrase);
    return strTok.countTokens();
}

Most frequent character

Using a common regular expression to split a string on each char and converting a string to a stream we collect using a reduction operation to group chars. The Collectors.counting() is a collector that accepts a char and counts the number of times it occurs. In the instance no elements are present, the result is 0.

Once the string is grouped and counted we will order the hashmap by value in descending order. This will have the highest to lowest value and to get the most frequent we will get the first entry.

public static String mostFrequent(String sentence) {

    // group existing chars together
    Map<String, Long> frequentChars = Arrays.stream(
            sentence.toLowerCase().split("")).collect(
            Collectors.groupingBy(c -> c, Collectors.counting()));

    // order highest to lowest
    Comparator<Entry<String, Long>> byValue = (entry1, entry2) -> entry1
        .getValue().compareTo(entry2.getValue());

    Optional<Entry<String, Long>> val = frequentChars.entrySet()
            .stream().sorted(byValue.reversed()).findFirst();

    return val.get().getKey();
}

Replace a string within string

To replace a string within a string, there is three parameters that need to be passed. First, the original string, second the string to find and finally the value to replace it with. The comments in the code will walk through additional logic.

public static String replaceSubString(String original,
        String findString, String replaceString) {

    // If string to find and the replace string are the same then return
    // original b/c there is nothing to replace
    if (findString.equals(replaceString)) {
        return original;
    }

    // Make a StringBuffer object for original.
    StringBuffer modifiedString = new StringBuffer(original);

    // Find the first occurrence of findstring.
    int index = modifiedString.indexOf(findString);

    while (index != -1) {
        // Replace this occurrence of the substring.
        modifiedString.replace(index, (index + findString.length()),
                replaceString);

        // Find the next occurrence of findString.
        index = modifiedString.indexOf(findString);
    }

    // Return the modified string.
    return modifiedString.toString();

}

Convert array to string

public static String arrayToString(char[] array) {
    String newString = String.valueOf(array);
    return newString;
}

Main program

public static void main(String[] args) {

    String phrase = "the dog jumped over the fence";

    // Number of words in a string
    System.out.println("Number of words in \"" + phrase + "\" is "
            + StringOperations.wordCount(phrase));

    // Show most frequent char
    System.out.println("Most frequently occurring character: "
            + StringOperations.mostFrequent(phrase));

    // Replace string
    System.out.println("Modified phrase replacing the with that: "
            + StringOperations.replaceSubString(phrase, "the", "that"));

    // Convert an array to a string and display it.
    String arrayToString = StringOperations.arrayToString(phrase
            .toCharArray());
    System.out.println("Converted arrayToString: " + arrayToString);
}

Output

Number of words in "the dog jumped over the fence" is 6
Most frequently occurring character: e
Modified phrase replacing the with that: that dog jumped over that fence
Converted arrayToString: the dog jumped over the fence