-2

Is there a way to create some type of For loop to separate a string with spaces? So far I can display a string and find how many characters it has.

import java.util.Scanner;
import java.lang.String;

public class Word{
  public static void main(String args[])
  {
     Scanner scan = new Scanner(System.in);

     int b;

    String word;

    System.out.println ("Enter a word: ");
    word = scan.next();

    b = word.length();

    System.out.println (word);
    System.out.println (b);
  }
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
jerms246
  • 61
  • 2
  • 2
  • 7

6 Answers6

8

As an alternative to Scanner, you can do something like the following:

String[] parts = line.split(" ");
for (String part : parts) {
    //do something interesting here
}
highlycaffeinated
  • 19,729
  • 9
  • 60
  • 91
2

Use the split() method in the String class, like this:

String line = "a series of words";
String[] words = line.split("\\s+");

It will return a String[] with the individual words in line, for the above example it will produce this:

{"a", "series", "of", "words"}
Óscar López
  • 232,561
  • 37
  • 312
  • 386
1

You can use String.split to split the sentence into an array of words.. something like

string[] words = word.split(" ");
for (String s: words)
{
    System.out.println(s);
    System.out.println("\n");
}
LarsH
  • 27,481
  • 8
  • 94
  • 152
Venkata Krishna
  • 14,926
  • 5
  • 42
  • 56
0

have you tried looking at the java API? there are a lot of different functions you can use ... top of my head split would work nicely and you wouldn't even have to write a loop

http://docs.oracle.com/javase/6/docs/api/

keshav
  • 866
  • 11
  • 19
0

This is untested, but I feel like this is a learning exercise so this should put you on the right path. In the for loop you access each character of the word as a sub-string and concatenate a space on the end (end of the word as well).

string word2 ="";
for (int i = 0; i<word.length-1;i++) {
    word2 = word.substring(i, i+1)+" ";
}
RyanS
  • 3,964
  • 3
  • 23
  • 37
  • Sorry, missed that, take a look at your previous code. You've done the same thing before. (consider substituting b) – RyanS Apr 06 '12 at 03:13
0

I am using following code:

Arrays.stream(yourString.split(" ")).forEach( element -> {
                // do something with each element
                System.out.println(element + "\n");
            });
StackOverflow
  • 116
  • 1
  • 6