I solved exercise 8 from Core Java for Impatient, chapter 1. This exercise is to implement a displayAllCombinations
method to display all substrings of the given string.
I would like to prove that following algorithm is valid in Java. I wonder if there is an easier solution?
package pl.hubot.exercises.corejava.r01.ex08;
import java.util.Scanner;
/**
* This program contains mine solutions of exercises
* from book Core Java for the Impatient, chapter 1.
*
* The content of following exercise:
* "Write a program that reads a string and displays all contained
* in it non-empty strings."
*
* @version 1.00 23-07-2016
* @author Hubot
*/
public class Program
{
public static void main(String[] args)
{
System.out.print("Enter any string: ");
Scanner in = new Scanner(System.in);
String text = in.nextLine();
displayAllCombinations(text);
}
private static void displayAllCombinations(String text)
{
int offset = 0;
int current = 0;
int ending = text.length();
while (offset != ending)
{
String result = text.substring(current, ending - offset);
if (!result.equals(""))
System.out.println(result);
if (current != (ending - offset)) current++;
else
{
current = 0;
offset++;
}
}
}
}
Sample run:
Enter any string: Amy Amy my y Am m A