繁体   English   中英

如何在不使用.split()的情况下计算字符串中的每个单词?

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

给定用户输入的String句子。 将每个单词与单词#分开打印。 例如,如果输入句子“戴帽子的猫”,则输出为以下内容

字1:
第2个字:猫
第3字:在
字4:
第5个字:帽子

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

要么

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

如果你想全部都在同一行

在for循环中,跟踪每个单词的起始索引(例如,将其存储在变量中)。 每当您碰到一个新空格时,请使用带有附加数字的子字符串打印出该单词。

您可能要处理一些情况。 如果句子以一堆空格开头或结尾,则需要处理该句子而不打印任何内容或增加字数。 如果单词之间有多个空格,则需要执行相同的操作。

以下代码分隔给定字符串的单词

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

这不是张贴作业的正确位置,无论如何,以下代码可以完成您想要的事情。 如果要打印单词,则需要存储它们,例如在列表或数组中。

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

该代码还应注意单词之间或句子结尾是否有多余的空格。 希望这会有所帮助。

您是否尝试过stringbuilder,还是可以将所有元素添加到arraylist中,然后对其进行计数。 或数一数。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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