0

Given a String sentence entered by the user. Print each word on a separate line with the word #. For example, If the sentence "The cat in the hat" was entered, the following would be the output

word #1: The
word #2: cat
word #3: in
word #4: the
word #5: hat

Scanner input = new Scanner (System.in);

String sentence;
String words = "";
int count = 1;

sentence = input.nextLine();


for (int i = 1; i < sentence.length(); i++)
{
  if (sentence.charAt(i) == ' ')
    count++;
}
{
  words = sentence.substring(0,sentence.indexOf(' '));
  System.out.println(words);
}
8
  • try stringtokenizer docs.oracle.com/javase/7/docs/api/java/util/… Commented May 11, 2016 at 17:25
  • I can't use stringtokenizer because I haven't learned it? Commented May 11, 2016 at 17:27
  • You didn't state why you can't use .split(). Commented May 11, 2016 at 17:27
  • because my teacher said I could do it without .split() plz help Thanks Commented May 11, 2016 at 17:28
  • 2
    First of all, you ignore the first character, by starting at index 1. Use int i = 0; . Commented May 11, 2016 at 17:28

5 Answers 5

4
String s = "The cat in the hat";
Scanner scan = new Scanner(s);
int wordNum = 1;
while(scan.hasNext()){
    String temp = scan.next();
    System.out.println("word#" + wordNum + ": \t" + temp);
    wordNum++;
}

or

System.out.print("word#" + wordNum + ": \t" + temp + "\t");

if you want all on the same line

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

1 Comment

Not sure who downvoted this, but his answer is correct.
0

In your for loop, keep track of the starting index of each word (e.g. store it in a variable). Whenever you hit a new space, print out the word using substring with the number appended to it.

A few cases you may want to handle. If the sentence begins or ends with a bunch of spaces, you need to handle this without printing anything or incrementing your word count. You will need to do the same if there are multiple spaces between words.

Comments

0

The following code separates the word of given string

import java.util.Scanner;
import java.util.StringTokenizer;

public class StringTokenDemo {

public static void main(String[] args) {

    Scanner sc=new Scanner(System.in);

    String sentence=sc.nextLine();

    StringTokenizer tokenizer=new StringTokenizer(sentence," ");
   int i=1;
    while (tokenizer.hasMoreTokens())
    {
        String token=(String)tokenizer.nextToken();
        System.out.println("#word"+i+" "+token);
        i++;
    }
 }
} 

1 Comment

OP has said that he cannot use String tokenizer.
0

This is not the right place to post homework, anyway the below code do what you want. If you want to print the words you need to store them, for example in a list or in an array.

List<String> words = new ArrayList<>();
String sentence = "The cat in the hat ";

int pos = 0;
int lastCharIndex = sentence.length() - 1 ; 
    for (int i = 0; i < sentence.length(); i++){
        char cur = sentence.charAt(i);
        //start to collect char for word only if 
        //the starting char is not a space  
        if(sentence.charAt(pos) == ' ' ){
            pos+=1;
            continue;
        }
        //continue the cycle if the current char is not a space
        // and it isn't the last char
        if(cur != ' ' && i != lastCharIndex){
            continue;       
        }
        //last word could not terminate with space
        if(i == lastCharIndex && cur != ' '){
            i+=1;
        }

        String word = sentence.substring(pos,i);
        pos=i;
        words.add(word);    
    }

    System.out.println(words);

the code also take care if extra space between word or at the end of the sentence. Hope this can help.

Comments

-1

did you try stringbuilder, or you can add all the elements in a arraylist and then count them. or count the chars.

Scanner input = new Scanner (System.in);
String sentence;
 String words = "";
  int count = 0;
  for(char c : input.toCharArray()){
   count++;
     }
 System.out.println("The word count is "+ count);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.