java 编写代码以使用方法查找字符串中的单词数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17238148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
write a code to find the number of words in a string using methods
提问by user2509405
I've been looking and I can't find anywhere how to write a word count using 3 methods. Here is what the code looks like so far. I'm lost on how to use the methods. I can do this without using different methods and just using one. Please help!!!
我一直在寻找,但在任何地方都找不到如何使用 3 种方法编写字数统计。到目前为止,代码如下所示。我迷失了如何使用这些方法。我可以不使用不同的方法而只使用一种方法来做到这一点。请帮忙!!!
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Enter a string: ");
String s = in.nextLine();
if (s.length() > 0)
{
getInputString(s);
}
else
{
System.out.println("ERROR - string must not be empty.");
System.out.print("Enter a string: ");
s = in.nextLine();
}
// Fill in the body with your code
}
// Given a Scanner, prompt the user for a String. If the user enters an empty
// String, report an error message and ask for a non-empty String. Return the
// String to the calling program.
private static String getInputString(String s) {
int count = getWordCount();
while (int i = 0; i < s.length(); i++)
{
if (s.charAt(i) == " ")
{
count ++;
}
}
getWordCount(count);
// Fill in the body
// NOTE: Do not declare a Scanner in the body of this method.
}
// Given a String return the number of words in the String. A word is a sequence of
// characters with no spaces. Write this method so that the function call:
// int count = getWordCount("The quick brown fox jumped");
// results in count having a value of 5. You will call this method from the main method.
// For this assignment you may assume that
// words will be separated by exactly one space.
private static int getWordCount(String input) {
// Fill in the body
}
}
EDIT: I have changed the code to
编辑:我已将代码更改为
private static String getInputString(String s) {
String words = getWordCount(s);
return words.length();
}
private static int getWordCount(String s) {
return s.split(" ");
}
But I can't get the string convert to integer.
但我无法将字符串转换为整数。
回答by Rick Suggs
You have read the name of the method, and look at the comments to decide what should be implemented inside the method, and the values it should return.
您已经阅读了方法的名称,并查看了注释来决定应该在方法内部实现什么,以及它应该返回的值。
The getInputString
method signature should be:
该getInputString
方法的签名应该是:
private static String getInputString(Scanner s) {
String inputString = "";
// read the input string from system in
// ....
return inputString;
}
The getWordCount
method signature should be:
该getWordCount
方法的签名应该是:
private static int getWordCount(String input) {
int wordCount = 0;
// count the number of words in the input String
// ...
return wordCount;
}
The main
method should look something like this:
该main
方法应如下所示:
public static void main(String[] args) {
// instantiate the Scanner variable
// call the getInputString method to ... you guessed it ... get the input string
// call the getWordCount method to get the word count
// Display the word count
}
回答by user2509405
count=1 //last word must be counted
for(int i=0;i<s.length();i++)
{
ch=s.charAt(i);
if(ch==' ')
{
count++;
}
}
回答by Bohemian
Use trim()
and split()
on 1-n whitespace chars:
在 1-n 个空白字符上使用trim()
和split()
:
private static int getWordCount(String s) {
return s.trim().split("\s+").length;
}
The call to trim()
is necessary, otherwise you'll get one extra "word" if there is leading spaces in the string.
调用 totrim()
是必要的,否则如果字符串中有前导空格,您将得到一个额外的“单词”。
The parameter "\\s+"
is necessary to count multiple spaces as a single word separator. \s
is the regex for "whitespace". +
is regex for "1 or more".
该参数"\\s+"
对于将多个空格计算为单个单词分隔符是必需的。\s
是“空白”的正则表达式。+
是“1 或更多”的正则表达式。
回答by user2509423
You can do this by :
你可以这样做:
private static int getWordCount(String input) {
return input.split("\s+").length;
}
回答by Rosdi Kasim
What you need to do is, count the number of spaces in the string. That is the number of words in the string.
您需要做的是,计算 string 中的空格数。那是字符串中的单词数。
You will see your count will be off by 1, but after some pondering and bug hunting you will figure out why.
您会看到您的计数将减少 1,但经过一些思考和 bug 搜寻后,您会找出原因。
Happy learning!
快乐学习!
回答by Edd
Based on your code i think this is what you're trying to do:
根据您的代码,我认为这就是您要执行的操作:
private static int getWordCount(String input) {
int count = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ' ') {
count++;
}
}
return count;
}
Here's what I've done:
这是我所做的:
- I've moved the code you were 'playing' with into the right method (
getWordCount
). - Corrected the loop you were trying to use (I think you have for and while loops confused)
- Fixed your check for the space character (
' '
not" "
)
- 我已将您正在“使用”的代码移至正确的方法 (
getWordCount
) 中。 - 更正了您尝试使用的循环(我认为您对 for 和 while 循环感到困惑)
- 修复了您对空格字符的检查(
' '
不是" "
)
There is a bug in this code which you'll need to work out how to fix:
这段代码中有一个错误,您需要弄清楚如何修复:
getWordCount("How are you");
will return 2 when it should be 3getWordCount("");
will return 0getWordCount("Hello");
will return 0 when it should be 1
getWordCount("How are you");
当它应该是 3 时将返回 2getWordCount("");
将返回 0getWordCount("Hello");
当它应该是 1 时将返回 0
Good luck!
祝你好运!
回答by Kedar1442
Better use simple function of spilt() with arguments as space
更好地使用 spilt() 的简单函数,参数为空格
int n= str.split(" ").length;
回答by Stephan
I'm not sure what trouble you're having with methods but I dont think you need more than one, try this: it uses split to split up the words in a string, and you can chose the delimeters
我不确定您在使用方法时遇到了什么麻烦,但我认为您不需要多个方法,试试这个:它使用 split 来拆分字符串中的单词,您可以选择分隔符
String sentence = "This is a sentence.";
String[] words = sentence.split(" ");
for (String word : words) {
System.out.println(word);
}
then you can do:
那么你可以这样做:
numberOfWords = words.length();
if you want to use 3 methods, you can call a method from your main()
method that does this for you, for example:
如果您想使用 3 种方法,您可以从您的main()
方法中调用一个为您执行此操作的方法,例如:
public String getInputString() {
Scanner in = new Scanner (System.in);
System.out.print("Enter a string: ");
String s = in.nextLine();
if (s.length() > 0) {
return s;
} else {
System.out.println("ERROR - string must not be empty.");
System.out.print("Enter a string: ");
return getInputString();
}
}
public int wordCount(String s) {
words = splitString(s)
return words.length();
}
public String[] splitString(String s) {
return s.split(" ");
}
回答by Nandkumar Tekale
Use String.split()
method like :
使用String.split()
方法如:
String[] words = s.split("\s+");
int wordCount = words.length;
回答by Manish Kumar Majumdar
public static int Repeat_Words(String arg1,String arg2)
{
//It find number of words can be formed from a given string
if(arg1.length() < 1 || arg2.length() < 1)
return 0;
int no_words = 99999;
char[] str1 = arg1.toCharArray();
char[] str2 = arg2.toCharArray();
for(int x = 0; x < str1.length; x++)
{
int temp = 0;
for(int y = 0; y < str2.length; y++)
{
if(str1[x] == str2[y])
temp++;
}
if(temp == 0)
return 0;
if(no_words > temp)
no_words = temp;
temp = 0;
}
return no_words;
}