Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at

Monday, December 22, 2014

How to separate words from String in java. Break the String in meaningful sentence.

Problem : Given an input string , separate the input string into a space-separated sequence of dictionary words if possible. For example, if the input string is "helloworld" then we would return the string "hello world" as output.

Assume you are given a Dictionary against which you can check the validity of words. Print "String can not be separated" if it contains numbers , any special character or any invalid combination of character/word.

Solution in java

 * Created by IN00474 on 22-12-2014.

import java.util.*;
public class StringToSentence {

    static List<String> l = new ArrayList<String>();
    static String wordToCheck = "";

    public static void main(String[] args) {
  if (args.length==0)
   System.out.println("Pass the input String");
        String inputString = args[0];
        if (inputString.matches("[a-zA-Z]+")) {
            for (int i = 0; i < inputString.length(); i++) {
                wordToCheck = wordToCheck + inputString.charAt(i);
                if (checkInDictionary(wordToCheck)) {
                    wordToCheck = "";
                        System.out.println("String can not be sorted");

        } else {
            System.out.println("String can not be sorted");

    public static boolean checkInDictionary(String wordToCheck) {
        ArrayList al = new ArrayList();
        if (al.contains(wordToCheck)) {
            return true;
        } else {
            return false;

    public static void displaySentence(List l) {
        Iterator i = l.iterator();
        while (i.hasNext()) {
            System.out.print((String) + " ");


Please note this code was tested against multiple use cases and return correct results, let us know if any of the use case if fails to pass.

Run time result

No comments: