1

I'm trying to write a program that will allow a user to input a phrase (for example: "I like cats") and print each word on a separate line. I have already written the part to allow a new line at every space but I don't want to have blank lines between the words because of excess spaces. I can't use any regular expressions such as String.split(), replaceAll() or trim().

I tried using a few different methods but I don't know how to delete spaces if you don't know the exact number there could be. I tried a bunch of different methods but nothing seems to work.

Is there a way I could implement it into the code I've already written?

  for (i=0; i<length-1;) {
      j = text.indexOf(" ", i); 
      if (j==-1) {
          j = text.length(); 
      }
      System.out.print("\n"+text.substring(i,j));
      i = j+1; 
  }

Or how can I write a new expression for it? Any suggestions would really be appreciated.

5
  • text.replaceAll(" ", "\n") OR if you want a list of lines, text.split("\n") Commented Mar 18, 2016 at 4:17
  • @Vilsol Read the question. Those can't be used Commented Mar 18, 2016 at 4:18
  • Sorry, didn't notice. Commented Mar 18, 2016 at 4:18
  • How is this replaceAll? If you want to print each word on a newline, sounds more like you want to implement split Commented Mar 18, 2016 at 4:21
  • Did you find any of the solutions below useful? if so, please consider leaving feedback by selecting one as the correct answer Commented Mar 18, 2016 at 6:14

6 Answers 6

2

I have already written the part to allow a new line at every space but I don't want to have blank lines between the words because of excess spaces.

If you can't use trim() or replaceAll(), you can use java.util.Scanner to read each word as a token. By default Scanner uses white space pattern as a delimiter for finding tokens. Similarly, you can also use StringTokenizer to print each word on new line.

String str = "I like    cats";
Scanner scanner = new Scanner(str);
while (scanner.hasNext()) {
    System.out.println(scanner.next());
}

OUTPUT

I
like
cats
Sign up to request clarification or add additional context in comments.

2 Comments

He is not allowed to use trim() or replaceAll()
Upvoted, this is actually pretty elegant. However, Scanner uses regular expressions internally, not sure if OP is fine with that.. if so, this answer is spot on
0

Here is a simple solution using substring() and indexOf()

public static void main(String[] args) {
    List<String> split = split("I like cats");
    split.forEach(System.out::println);
}

public static List<String> split(String s){
    List<String> list = new ArrayList<>();
    while(s.contains(" ")){
        int pos = s.indexOf(' ');
        list.add(s.substring(0, pos));
        s = s.substring(pos + 1);
    }
    list.add(s);
    return list;
}

Edit:

If you only want to print the text without splitting or making lists, you can use this:

public static void main(String[] args) {
    newLine("I like cats");
}

public static void newLine(String s){
    while(s.contains(" ")){
        int pos = s.indexOf(' ');
        System.out.println(s.substring(0, pos));
        s = s.substring(pos + 1);
    }
    System.out.println(s);
}

Comments

0

I think this will solve your problem.

public static List<String> getWords(String text) {
    List<String> words = new ArrayList<>();
    BreakIterator breakIterator = BreakIterator.getWordInstance();
    breakIterator.setText(text);
    int lastIndex = breakIterator.first();
    while (BreakIterator.DONE != lastIndex) {
        int firstIndex = lastIndex;
        lastIndex = breakIterator.next();
        if (lastIndex != BreakIterator.DONE && Character.isLetterOrDigit(text.charAt(firstIndex))) {
            words.add(text.substring(firstIndex, lastIndex));
        }
    }

    return words;
}

public static void main(String[] args) {
    String text = "I like         cats";
    List<String> words = getWords(text);
    for (String word : words) {
        System.out.println(word);
    }
}

Output :

I
like
cats

Comments

0

What about something like this, its O(N) time complexity: Just use a string builder to create the string as you iterate through your string, add "\n" whenever you find a space

    String word = "I like cats";
    StringBuilder sb = new StringBuilder();
    boolean newLine = true;
    for(int i = 0; i < word.length(); i++) {
        if (word.charAt(i) == ' ') {
            if (newLine) {
                sb.append("\n");
                newLine = false;
            }
        } else {
            newLine = true;
            sb.append(word.charAt(i));
        }
    }

    String result = sb.toString();

EDIT: Fixed the problem mentioned on comments (new line on multiple spaces)

2 Comments

This will result in extra newlines when there are multiple spaces together.
Fixed the multiple spaces problem
0

Sorry, I didnot caution you cannot use replaceAll().

This is my other solution:

    String s = "I like   cats";
    Pattern p = Pattern.compile("([\\S])+");
    Matcher m = p.matcher(s);
      while (m.find( )) {
          System.out.println(m.group());
      }

Old solution:

    String s = "I like   cats";
    System.out.println(s.replaceAll("( )+","\n"));

Comments

-1

You almost done all job. Just make small addition, and your code will work as you wish:

for (int i = 0; i < length - 1;) {
  j = text.indexOf(" ", i);

  if (i == j) { //if next space after space, skip it
    i = j + 1;
    continue;
  }

  if (j == -1) {
    j = text.length();
  }
  System.out.print("\n" + text.substring(i, j));
  i = j + 1;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.