[英]Letter count in sentence not counting last word
I am new to java programming. 我是Java编程的新手。 This snippet calculates no of letters in each word and stores it as a string(excluding the spaces) but it is only calculating till "large" and not counting no of letters in "container".
该代码段不计算每个单词中的字母并将其存储为字符串(不包括空格),但仅计算到“大”,而不计算“容器”中的字母。
class piSong
{
String pi = "31415926535897932384626433833";
public void isPiSong(String exp)
{
int i,count=0;
String counter = "";
String str;
System.out.println(exp.charAt(25));
for(i=0;i<exp.length()-1;i++)
{
if(Character.isWhitespace(exp.charAt(i)))
{ str = Integer.toString(count);
counter += str;
count = 0;
continue;
}
count++;
}
System.out.println(counter);
}
}
public class isPiSong{
public static void main(String[] args)
{
piSong p = new piSong();
String exp = "can i have a large container";
p.isPiSong(exp);
}
}
expected output:314157 预期产量:314157
current output: 31415 电流输出:31415
There are 2 things you should fix. 您应该修复两件事。
In your for loop, your condition is i<exp.length()-1
. 在for循环中,条件为
i<exp.length()-1
。 Why? 为什么? You obviously want to include the last character also (which is
charAt(exp.length() -1)
), so you condition should either be i <= exp.length() -1
or i < exp.length()
. 您显然也想包括最后一个字符(
charAt(exp.length() -1)
),因此您的条件应该是i <= exp.length() -1
或i < exp.length()
。
You logic is to count the letters whenever you encounter a whitespace. 您的逻辑是每当遇到空白时都要计算字母。 But after counting the last word, you dont have a whitespace.
但是在计算完最后一个字之后,您没有空格。 That's why it's not counting the last word.
这就是为什么它不算最后一个字。
To Fix, append count
to counter
after the loop. 要解决此问题,请在循环后将
count
附加到counter
。
// Loop ends here
counter += count;
System.out.println(counter);
String counter = "";
String[] array = exp.split(" ");
for(String s: array){
counter += Integer.toString(s.length);
}
The second line splits the String into an array of strings (splits using each instance of a space in the String). 第二行将String拆分为字符串数组(使用String中的空格的每个实例进行拆分)。 The loop goes through each individual String in the array and adds its length to the counter String.
循环遍历数组中的每个单独的String,并将其长度添加到计数器String。 It's preferable to use a
StringBuilder
instead of +=
to append to a String. 最好使用
StringBuilder
而不是+=
附加到String。
StringBuilder sb = new StringBuilder();
String[] array = exp.split(" ");
for(String s: array){
sb.append(Integer.toString(s.length));
}
String counter = sb.toString();
But both will do the same. 但是两者都会做同样的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.