Examples

In this section, we will work several additional examples of full Java programs that involve string manipulation.

Example 1: encryption

Secret messages (such as secure email, online credit card purchases, online banking, etc.) are often transmitted using encryption. When one of these messages is sent, it is encrypted by altering the message in some way that makes it unrecognizable at face value. The recipient can then “undo” this encryption to get back the original message. The idea is that ONLY the recipient can get back the original message (usually because they know some extra piece of information about how the message was transformed), and that others snooping in will just see gibberish.

In this example, we will write a very basic encryption algorithm. For each letter in the message, we will replace it with the letter that comes three after it in the alphabet. For example, ‘A’ becomes ‘D’, ‘B’ becomes ‘E’, etc. When we get to the end of the alphabet, we will wrap around to the beginning (so ‘Z’ becomes ‘C’, etc.). This program will ask for a message and if the user wants to encrypt or decrypt (““ndo” the encryption), and will then print out the resulting message.

import java.io.*;
public class Encrypt 
{
    public static void main(String[] args) 
    {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter a message: ");
        String msg = s.nextLine();

        System.out.println("Enter (e)ncrypt or (d)ecrypt: ");
        char eOrD = (s.nextLine()).charAt(0);

        String result = "";
        String alpha = "abcdefghijklmnopqrstuvwxyz";

        //this program assumes all lower-case characters
        if (eOrD == 'e') 
        {
            for (int i = 0; i < msg.length(); i++) 
            {
                String cur = msg.substring(0,1);

                //get where that letter is in the alphabet
                int index = alpha.indexOf(cur);

                //shift it down 3 (wrapping around)
                index = (index + 3) % 26;

                //get letter at the new spot, add to result
                cur = alpha.substring(index, index+1);
                alpha += cur;
            }
        }
        else if (eOrD == 'd') {
            for (int i = 0; i < msg.length(); i++) 
            {
                String cur = msg.substring(0,1);

                //get where that letter is in the alphabet
                int index = alpha.indexOf(cur);

                //shift it back 3 (wrapping, making sure not <0)
                index = (index  3 + 26) % 26;
                
                //get letter at the new spot, add to result
                cur = alpha.substring(index, index+1);
                alpha += cur;
            }
        }
        else 
        {
            System.out.println("Invalid input");
        }

        System.out.printf("Result: %s%n", result);
    }
}

Example 2: print all substrings

In this example, we will write a program that gets an input string, and then prints all possible substrings of that string.

import java.util.*;
public class Substrings 
{
    public static void main(String[] args) 
    {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = s.nextLine();

        //loop through all starting positions
        for (int i = 0; i < str.length(); i++) 
        {
            //loop through all STOPPING positions if we start at i
            for (int j = i+1; j <= str.length(); j++) 
            {
                //get substring from i up to but not including j
                String piece = str.substring(i,j);
                System.out.println(piece);
            }
        }
    }
}

Example 3: Pig Latin

In this example, we will write a Pig Latin converter, where the user enters a sentence and the program translates it to Pig Latin. The rules we’ll use (there are several variations, but we’ll keep it simple) for converting an English word to Pig Latin are as follows:

  • If a word begins with a consonant, the consonant is moved to the end of the word and “ay” is added, like this: “cake” -> “ake-cay”
  • If a word begins with a vowel, “way” is added to the end of the word, like this: “is” -> “is-way”
import java.util.*;
//this program assumes letters are lower-case and that words are separated only by spaces
public class PigLatin 
{
    public static void main(String[] args) 
    {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter a sentence: ");
        String str = s.nextLine();
        String result = "";

        //y can be a vowel too, but we’re ignoring this case
        String vowels = "aeiou";

        //get each word
        StringTokenizer tok = new StringTokenizer(str, " ");

        while (tok.hasMoreTokens()) 
        {
            String word = tok.nextToken();
            String first = word.substring(0,1);

            //if word begins with a vowel
            if (vowels.indexOf(first) >= 0) 
            {
                //concatenate "way" to end of word
                result += word + "-way ";
            }
            else 
            {
                //word is a consonant
                String rest = word.substring(1,word.length());
                result += rest + "-" + first + "ay ";
            }
        }
        System.out.printf("In Pig Latin: %s%n", result);
    }
}

The way we are constructing the result string is somewhat inefficient because strings are an immutable type. This means that any time we concatenate onto a string, we are actually creating memory for a new string and copying all the characters over. In class, we will also learn about the StringBuilder type, which we can use to build string results much more efficiently.