Home > Software engineering >  Split a user-written String separated by spaces. (splitString) Java
Split a user-written String separated by spaces. (splitString) Java

Time:11-07

So far I've got this program which asks me to write a sentence, then it splits it one word at a time separated by spaces. The problem is that if I write a 3 word sentence it just prints the first two words. What I'm trying to do is split the sentence with no word limit. I just talked to my teacher and he said I must use the subString method instead of the splitString one. Any ideas?

The code:

package NF2;

import java.util.Scanner;

public class Exercici13 {
    public static void main(String[] args) {
        //Declaring variables
        Scanner ent = new Scanner(System.in);
        String sentence;


        //LLegim frase
        System.out.println("Enter a non-empty text: ");
        sentence = ent.nextLine();
        if(sentence.length() == 0){
            System.out.println("You haven't written anything, exiting the program...");
            System.exit(0);

        }

        //Separate by spaces
        String[] splitString = sentence.split(" ");
        System.out.println(splitString[0]);
        System.out.println(splitString[1]);

    }
}

For example, if I write a 3 word sentence now it only returns me the first two words. Plus I can only use the subString, so I should re-do it all over again and I'm not sure where to start. Keep in mind I'm a total begginner, so it's not okay to use advanced methods.

CodePudding user response:

Your code only prints two words. To print a third word you would need yet another println, like so:

String[] splitString = sentence.split(" ");
System.out.println(splitString[0]);
System.out.println(splitString[1]);
System.out.println(splitString[2]);

To be able to print any length of sentence, you would not hardcode two or three but have a loop repeating for the amount of words found:

String[] splitString = sentence.split(" ");
for (int i=0; i<splitString.length; i  ) {
    System.out.println(splitString[i]);
}

CodePudding user response:

    System.out.println(
      String.join("\n",
       sentence.split("\\s")
      )
    );
  • Related