用字符串方法计算单词数?

发布于 2024-11-04 20:13:23 字数 124 浏览 1 评论 0原文

我想知道如何编写一个方法来仅使用 charAt、length 或 substring 等字符串方法来计算 java 字符串中的单词数。

循环和 if 语句都可以!

我真的很感谢我能得到的任何帮助!谢谢!

I was wondering how I would write a method to count the number of words in a java string only by using string methods like charAt, length, or substring.

Loops and if statements are okay!

I really appreciate any help I can get! Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

霓裳挽歌倾城醉 2024-11-11 20:13:23

即使使用多个空格、前导和/或尾随空格以及空行,这也适用:

String trim = s.trim();
if (trim.isEmpty())
    return 0;
return trim.split("\\s+").length; // separate string around spaces

有关 split 的更多信息 此处。

This would work even with multiple spaces and leading and/or trailing spaces and blank lines:

String trim = s.trim();
if (trim.isEmpty())
    return 0;
return trim.split("\\s+").length; // separate string around spaces

More info about split here.

隱形的亼 2024-11-11 20:13:23
public static int countWords(String s){

    int wordCount = 0;

    boolean word = false;
    int endOfLine = s.length() - 1;

    for (int i = 0; i < s.length(); i++) {
        // if the char is a letter, word = true.
        if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
            word = true;
            // if char isn't a letter and there have been letters before,
            // counter goes up.
        } else if (!Character.isLetter(s.charAt(i)) && word) {
            wordCount++;
            word = false;
            // last word of String; if it doesn't end with a non letter, it
            // wouldn't count without this.
        } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
            wordCount++;
        }
    }
    return wordCount;
}
public static int countWords(String s){

    int wordCount = 0;

    boolean word = false;
    int endOfLine = s.length() - 1;

    for (int i = 0; i < s.length(); i++) {
        // if the char is a letter, word = true.
        if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
            word = true;
            // if char isn't a letter and there have been letters before,
            // counter goes up.
        } else if (!Character.isLetter(s.charAt(i)) && word) {
            wordCount++;
            word = false;
            // last word of String; if it doesn't end with a non letter, it
            // wouldn't count without this.
        } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
            wordCount++;
        }
    }
    return wordCount;
}
饮湿 2024-11-11 20:13:23

嗨,我刚刚想出了这样的 StringTokenizer:

String words = "word word2 word3 word4";
StringTokenizer st = new Tokenizer(words);
st.countTokens();

Hi I just figured out with StringTokenizer like this:

String words = "word word2 word3 word4";
StringTokenizer st = new Tokenizer(words);
st.countTokens();
酒中人 2024-11-11 20:13:23

只需使用 ,

str.split("\\w+").length ;

Simply use ,

str.split("\\w+").length ;
享受孤独 2024-11-11 20:13:23
public static int countWords(String str){
        if(str == null || str.isEmpty())
            return 0;

        int count = 0;
        for(int e = 0; e < str.length(); e++){
            if(str.charAt(e) != ' '){
                count++;
                while(str.charAt(e) != ' ' && e < str.length()-1){
                    e++;
                }
            }
        }
        return count;
    }
public static int countWords(String str){
        if(str == null || str.isEmpty())
            return 0;

        int count = 0;
        for(int e = 0; e < str.length(); e++){
            if(str.charAt(e) != ' '){
                count++;
                while(str.charAt(e) != ' ' && e < str.length()-1){
                    e++;
                }
            }
        }
        return count;
    }
待"谢繁草 2024-11-11 20:13:23
 private static int countWordsInSentence(String input) {
    int wordCount = 0;

    if (input.trim().equals("")) {
        return wordCount;
    }
    else {
        wordCount = 1;
    }

    for (int i = 0; i < input.length(); i++) {
        char ch = input.charAt(i);
        String str = new String("" + ch);
        if (i+1 != input.length() && str.equals(" ") && !(""+ input.charAt(i+1)).equals(" ")) {
            wordCount++;
        }
    }

    return wordCount;
 }
 private static int countWordsInSentence(String input) {
    int wordCount = 0;

    if (input.trim().equals("")) {
        return wordCount;
    }
    else {
        wordCount = 1;
    }

    for (int i = 0; i < input.length(); i++) {
        char ch = input.charAt(i);
        String str = new String("" + ch);
        if (i+1 != input.length() && str.equals(" ") && !(""+ input.charAt(i+1)).equals(" ")) {
            wordCount++;
        }
    }

    return wordCount;
 }
御弟哥哥 2024-11-11 20:13:23

使用

myString.split("\\s+");

这个就可以了。

Use

myString.split("\\s+");

This will work.

婴鹅 2024-11-11 20:13:23

有一个简单的解决方案您可以尝试此代码

    String s = "hju   vg    jhdgsf  dh gg    g g  g  ";

    String[] words = s.trim().split("\\s+");

    System.out.println("count is = "+(words.length));

There is a Simple Solution You can Try this code

    String s = "hju   vg    jhdgsf  dh gg    g g  g  ";

    String[] words = s.trim().split("\\s+");

    System.out.println("count is = "+(words.length));
倾城月光淡如水﹏ 2024-11-11 20:13:23
public static int countWords(String input) {
        int wordCount = 0;
        boolean isBlankSet = false;
        input = input.trim();

        for (int j = 0; j < input.length(); j++) {
            if (input.charAt(j) == ' ')
                isBlankSet = true;
            else {
                if (isBlankSet) {
                    wordCount++;
                    isBlankSet = false;
                }
            }

        }

        return wordCount + 1;
    }
public static int countWords(String input) {
        int wordCount = 0;
        boolean isBlankSet = false;
        input = input.trim();

        for (int j = 0; j < input.length(); j++) {
            if (input.charAt(j) == ' ')
                isBlankSet = true;
            else {
                if (isBlankSet) {
                    wordCount++;
                    isBlankSet = false;
                }
            }

        }

        return wordCount + 1;
    }
海螺姑娘 2024-11-11 20:13:23

O(N) 中的算法

 count : 0;

 if(str[0] == validChar ) :
      count++;
 else :
      for i = 1 ; i < sizeOf(str) ; i++ :

          if(str[i] == validChar AND str[i-1] != validChar)

             count++;

          end if;

      end for;

 end if;

 return count;

Algo in O(N)

 count : 0;

 if(str[0] == validChar ) :
      count++;
 else :
      for i = 1 ; i < sizeOf(str) ; i++ :

          if(str[i] == validChar AND str[i-1] != validChar)

             count++;

          end if;

      end for;

 end if;

 return count;
歌入人心 2024-11-11 20:13:23
    import com.google.common.base.Optional;
    import com.google.common.base.Splitter;
    import com.google.common.collect.HashMultiset;
    import com.google.common.collect.ImmutableSet;
    import com.google.common.collect.Multiset;

    String str="Simple Java Word Count count Count Program";
    Iterable<String> words = Splitter.on(" ").trimResults().split(str);


    //google word counter       
    Multiset<String> wordsMultiset = HashMultiset.create();
    for (String string : words) {   
        wordsMultiset.add(string.toLowerCase());
    }

    Set<String> result = wordsMultiset.elementSet();
    for (String string : result) {
        System.out.println(string+" X "+wordsMultiset.count(string));
    }


add at the pom.xml
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>r09</version>
</dependency>
    import com.google.common.base.Optional;
    import com.google.common.base.Splitter;
    import com.google.common.collect.HashMultiset;
    import com.google.common.collect.ImmutableSet;
    import com.google.common.collect.Multiset;

    String str="Simple Java Word Count count Count Program";
    Iterable<String> words = Splitter.on(" ").trimResults().split(str);


    //google word counter       
    Multiset<String> wordsMultiset = HashMultiset.create();
    for (String string : words) {   
        wordsMultiset.add(string.toLowerCase());
    }

    Set<String> result = wordsMultiset.elementSet();
    for (String string : result) {
        System.out.println(string+" X "+wordsMultiset.count(string));
    }


add at the pom.xml
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>r09</version>
</dependency>
沫离伤花 2024-11-11 20:13:23

计算字符串中的单词数:

这也可能有帮助 -->

package data.structure.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CountWords {

    public static void main(String[] args) throws IOException {
// Couting number of words in a string
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("enter Your String");
        String input = br.readLine(); 

        char[] arr = input.toCharArray();
        int i = 0;
    boolean notCounted = true;
    int counter = 0;
    while (i < arr.length) {
        if (arr[i] != ' ') {
            if (notCounted) {
                notCounted = false;
                counter++;
            }
        } else {
            notCounted = true;
        }
        i++;
    }
    System.out.println("words in the string are : " + counter);
}

}

Counting Words in a String:

This might also help -->

package data.structure.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CountWords {

    public static void main(String[] args) throws IOException {
// Couting number of words in a string
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("enter Your String");
        String input = br.readLine(); 

        char[] arr = input.toCharArray();
        int i = 0;
    boolean notCounted = true;
    int counter = 0;
    while (i < arr.length) {
        if (arr[i] != ' ') {
            if (notCounted) {
                notCounted = false;
                counter++;
            }
        } else {
            notCounted = true;
        }
        i++;
    }
    System.out.println("words in the string are : " + counter);
}

}
痕至 2024-11-11 20:13:23
public class TestStringCount {

  public static void main(String[] args) {
    int count=0;
    boolean word= false;
    String str = "how ma ny wo rds are th ere in th is sente nce";
    char[] ch = str.toCharArray();
    for(int i =0;i<ch.length;i++){
        if(!(ch[i]==' ')){
            for(int j=i;j<ch.length;j++,i++){
                if(!(ch[j]==' ')){
                    word= true;
                    if(j==ch.length-1){
                        count++;
                    }
                    continue;
                }
                else{
                    if(word){
                        count++;
                    }
                    word = false;
                }
            }
        }
        else{
            continue;
        }
    }
    System.out.println("there are "+(count)+" words");      
    }
}
public class TestStringCount {

  public static void main(String[] args) {
    int count=0;
    boolean word= false;
    String str = "how ma ny wo rds are th ere in th is sente nce";
    char[] ch = str.toCharArray();
    for(int i =0;i<ch.length;i++){
        if(!(ch[i]==' ')){
            for(int j=i;j<ch.length;j++,i++){
                if(!(ch[j]==' ')){
                    word= true;
                    if(j==ch.length-1){
                        count++;
                    }
                    continue;
                }
                else{
                    if(word){
                        count++;
                    }
                    word = false;
                }
            }
        }
        else{
            continue;
        }
    }
    System.out.println("there are "+(count)+" words");      
    }
}
我做我的改变 2024-11-11 20:13:23

导入 java.util.;
导入java.io。

公共类主要{

public static void main(String[] args) {

    File f=new File("src/MyFrame.java");
    String value=null;
    int i=0;
    int j=0;
    int k=0;
try {
    Scanner  in =new Scanner(f);
    while(in.hasNextLine())
    {
    String a=in.nextLine();
    k++; 
    char chars[]=a.toCharArray();
    i +=chars.length;
    }
    in.close();
    Scanner in2=new Scanner(f);
    while(in2.hasNext())
            {

        String b=in2.next();
        System.out.println(b);
        j++;
            }
   in2.close();

    System.out.println("the number of chars is :"+i);
    System.out.println("the number of words is :"+j);
    System.out.println("the number of lines is :"+k);





}
catch (Exception e) {
    e.printStackTrace();

}


}

}

import java.util.;
import java.io.
;

public class Main {

public static void main(String[] args) {

    File f=new File("src/MyFrame.java");
    String value=null;
    int i=0;
    int j=0;
    int k=0;
try {
    Scanner  in =new Scanner(f);
    while(in.hasNextLine())
    {
    String a=in.nextLine();
    k++; 
    char chars[]=a.toCharArray();
    i +=chars.length;
    }
    in.close();
    Scanner in2=new Scanner(f);
    while(in2.hasNext())
            {

        String b=in2.next();
        System.out.println(b);
        j++;
            }
   in2.close();

    System.out.println("the number of chars is :"+i);
    System.out.println("the number of words is :"+j);
    System.out.println("the number of lines is :"+k);





}
catch (Exception e) {
    e.printStackTrace();

}


}

}

夜空下最亮的亮点 2024-11-11 20:13:23

我对该计划的想法是:

package text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CoutingWords {

    public static void main(String[] args) throws IOException {
        String str;
        int cWords = 1;
        char ch;

        BufferedReader buffor = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Enter text: ");
        str = buffor.readLine();

        for(int i =0; i<str.length(); i++){
            ch = str.charAt(i);
            if(Character.isWhitespace(ch)){ cWords++; }
        }
        System.out.println("There are " + (int)cWords +" words.");
    }
}

My idea of that program is that:

package text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CoutingWords {

    public static void main(String[] args) throws IOException {
        String str;
        int cWords = 1;
        char ch;

        BufferedReader buffor = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Enter text: ");
        str = buffor.readLine();

        for(int i =0; i<str.length(); i++){
            ch = str.charAt(i);
            if(Character.isWhitespace(ch)){ cWords++; }
        }
        System.out.println("There are " + (int)cWords +" words.");
    }
}
记忆之渊 2024-11-11 20:13:23

我是 stackoverflow 的新手,但我希望我的代码有帮助:

private int numOfWordsInLineCounter(String line){

     int words = 0;

         for(int i = 1 ; i<line.length();i++){
         Character ch  = line.charAt(i-1);
         Character bch = line.charAt(i);
             if(Character.isLetterOrDigit(ch) == true && Character.isLetterOrDigit(bch)== false ) words++;
             if(i == line.length()-1 && Character.isLetterOrDigit(bch))words++;
         }
     return words;
 } 

I'm new to stackoverflow but I hope my code helps:

private int numOfWordsInLineCounter(String line){

     int words = 0;

         for(int i = 1 ; i<line.length();i++){
         Character ch  = line.charAt(i-1);
         Character bch = line.charAt(i);
             if(Character.isLetterOrDigit(ch) == true && Character.isLetterOrDigit(bch)== false ) words++;
             if(i == line.length()-1 && Character.isLetterOrDigit(bch))words++;
         }
     return words;
 } 
睡美人的小仙女 2024-11-11 20:13:23

字符串短语通常由空格分隔的单词组成。那么,您可以使用空格作为分隔字符来分割短语,并按如下方式对它们进行计数。

import java.util.HashMap;

import java.util.Map;

public class WordCountMethod {

    public static void main (String [] args){

        Map<String, Integer>m = new HashMap<String, Integer>();
        String phrase = "hello my name is John I repeat John";
        String [] array = phrase.split(" ");

        for(int i =0; i < array.length; i++){
            String word_i = array[i];
            Integer ci = m.get(word_i);
            if(ci == null){
                m.put(word_i, 1);
            }
            else m.put(word_i, ci+1);
        }

        for(String s : m.keySet()){
            System.out.println(s+" repeats "+m.get(s));
        }
    }

} 

A string phrase normaly has words separated by space. Well you can split the phrase using the spaces as separating characters and count them as follows.

import java.util.HashMap;

import java.util.Map;

public class WordCountMethod {

    public static void main (String [] args){

        Map<String, Integer>m = new HashMap<String, Integer>();
        String phrase = "hello my name is John I repeat John";
        String [] array = phrase.split(" ");

        for(int i =0; i < array.length; i++){
            String word_i = array[i];
            Integer ci = m.get(word_i);
            if(ci == null){
                m.put(word_i, 1);
            }
            else m.put(word_i, ci+1);
        }

        for(String s : m.keySet()){
            System.out.println(s+" repeats "+m.get(s));
        }
    }

} 
┊风居住的梦幻卍 2024-11-11 20:13:23

以所选答案为起点,以下内容涉及一些英语语言问题,包括连字符、所有格和缩写的撇号、数字以及 UTF-16 之外的任何字符:

public static int countWords(final String s) {
    int wordCount = 0;
    boolean word = false;
    final int endOfLine = s.length() - 1;

    for (int i = 0; i < s.length(); i++) {
        // if the char is a letter, word = true.
        if (isWordCharacter(s, i) && i != endOfLine) {
            word = true;
            // if char isn't a letter and there have been letters before,
            // counter goes up.
        } else if (!isWordCharacter(s, i) && word) {
            wordCount++;
            word = false;
            // last word of String; if it doesn't end with a non letter, it
            // wouldn't count without this.
        } else if (isWordCharacter(s, i) && i == endOfLine) {
            wordCount++;
        }
    }
    return wordCount;
}

private static boolean isWordCharacter(final String s, final int i) {
    final char ch = s.charAt(i);
    return Character.isLetterOrDigit(ch)
            || ch == '\''
            || Character.getType(ch) == Character.DASH_PUNCTUATION
            || Character.isSurrogate(ch);
}

Taking the chosen answer as a starting point the following deals with a few English language issues including hyphenated words, apostrophes for possessives and shortenings, numbers and also any characters outside of UTF-16:

public static int countWords(final String s) {
    int wordCount = 0;
    boolean word = false;
    final int endOfLine = s.length() - 1;

    for (int i = 0; i < s.length(); i++) {
        // if the char is a letter, word = true.
        if (isWordCharacter(s, i) && i != endOfLine) {
            word = true;
            // if char isn't a letter and there have been letters before,
            // counter goes up.
        } else if (!isWordCharacter(s, i) && word) {
            wordCount++;
            word = false;
            // last word of String; if it doesn't end with a non letter, it
            // wouldn't count without this.
        } else if (isWordCharacter(s, i) && i == endOfLine) {
            wordCount++;
        }
    }
    return wordCount;
}

private static boolean isWordCharacter(final String s, final int i) {
    final char ch = s.charAt(i);
    return Character.isLetterOrDigit(ch)
            || ch == '\''
            || Character.getType(ch) == Character.DASH_PUNCTUATION
            || Character.isSurrogate(ch);
}
め七分饶幸 2024-11-11 20:13:23

我只是把这个放在一起。 wordCount() 方法中的增量器对我来说有点不优雅,但它确实有效。

import java.util.*;

public class WordCounter {

private String word;
private int numWords;

public int wordCount(String wrd) {
    StringTokenizer token = new StringTokenizer(wrd, " ");
    word = token.nextToken();
    numWords = token.countTokens();
    numWords++;

    return numWords;
}

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    String userWord;

    WordCounter wc = new WordCounter();

    System.out.println("Enter a sentence.");
    userWord = input.nextLine();

    wc.wordCount(userWord);

    System.out.println("You sentence was " + wc.numWords + " words long.");
  }
}

I just put this together. The incrementer in the wordCount() method is a bit inelegant to me, but it works.

import java.util.*;

public class WordCounter {

private String word;
private int numWords;

public int wordCount(String wrd) {
    StringTokenizer token = new StringTokenizer(wrd, " ");
    word = token.nextToken();
    numWords = token.countTokens();
    numWords++;

    return numWords;
}

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    String userWord;

    WordCounter wc = new WordCounter();

    System.out.println("Enter a sentence.");
    userWord = input.nextLine();

    wc.wordCount(userWord);

    System.out.println("You sentence was " + wc.numWords + " words long.");
  }
}
不美如何 2024-11-11 20:13:23

创建变量计数、状态。初始化变量
如果存在空间,则保持计数,否则增加计数。
例如:

if (string.charAt(i) == ' ' ) {
state = 0;
} else if (state == 0) {
state = 1;
count += 1;

create variable count, state. initialize variables
if space is present keep count as it is else increase count.
for eg:

if (string.charAt(i) == ' ' ) {
state = 0;
} else if (state == 0) {
state = 1;
count += 1;
扎心 2024-11-11 20:13:23

lambda,其中无需对计数的单词进行拆分和存储
并且完成计数

String text = "counting w/o apostrophe's problems or consecutive   spaces";

int count = text.codePoints().boxed().collect(
    Collector.of(
        () -> new int[] {0, 0},
        (a, c) -> {
          if( ".,; \t".indexOf( c ) >= 0 )
            a[1] = 0;
          else if( a[1]++ == 0 ) a[0]++;
        }, (a, b) -> {a[0] += b[0]; return( a );},
        a -> a[0] ) );

得到:7< /代码>

用作状态机,计算从空格字符 .,; 开始的转换。 \t 转为单词

lambda, in which splitting and storing of the counted words is dispensed with
and only counting is done

String text = "counting w/o apostrophe's problems or consecutive   spaces";

int count = text.codePoints().boxed().collect(
    Collector.of(
        () -> new int[] {0, 0},
        (a, c) -> {
          if( ".,; \t".indexOf( c ) >= 0 )
            a[1] = 0;
          else if( a[1]++ == 0 ) a[0]++;
        }, (a, b) -> {a[0] += b[0]; return( a );},
        a -> a[0] ) );

gets: 7

works as a status machine that counts the transitions from spacing characters .,; \t to words

潇烟暮雨 2024-11-11 20:13:23
if(str.isEmpty() || str.trim().length() == 0){
   return 0;
}
return (str.trim().split("\\s+").length);
if(str.isEmpty() || str.trim().length() == 0){
   return 0;
}
return (str.trim().split("\\s+").length);
小耗子 2024-11-11 20:13:23
    String a = "Some String";
    int count = 0;
    for (int i = 0; i < a.length(); i++) {

        if (Character.isWhitespace(a.charAt(i))) {
            count++; 
        }
    }
    System.out.println(count+1);

它将计算空格。但是,如果我们在 count 中加 1,我们就可以获得精确的单词。

    String a = "Some String";
    int count = 0;
    for (int i = 0; i < a.length(); i++) {

        if (Character.isWhitespace(a.charAt(i))) {
            count++; 
        }
    }
    System.out.println(count+1);

It will count white spaces. However, If we add 1 in count , we can get exact words.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文