简体   繁体   中英

How to count each word in a string without .split()?

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);
}
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

In your for loop, keep track of the starting index of each word (eg 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.

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++;
    }
 }
} 

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM