java - 分别分析字符串的每个单词

标签 java arrays string

当我试图分别分析一个字符串的每个单词时,第一个单词做得很好,但其余的我都失败了。帮助我更正此 JAVA 代码以获得正确的输出:

public class Test {

 public static void main(String[] args) {


            int count1=0;
    int chars_not_x=0 ;

String str = "xyz xyxzghz zyxzz";
    String[] words = str.split("\\s");

for(int m=0; m<words.length; m++){

            System.out.println(words[m]);

            System.out.println("Total characters in the word: "+words[m].length());
    for(int n=0; n<words[m].length(); n++){
if(words[m].charAt(n)=='x'){count1++;}}

           System.out.println("Number of x :"+count1);
           chars_not_x= words[m].length()- count1; 
           System.out.println("Chars other than x: "+chars_not_x);

           System.out.println("\n");


  }} }

代码的输出是"

xyz
Total characters in the word: 3
Number of x :1
Chars other than x: 2


xyxzghz
Total characters in the word: 7
Number of x :3
Chars other than x: 4


zyxzz
Total characters in the word: 5
Number of x :4
Chars other than x: 1

所需的输出:

xyz
Total characters in the word: 3
Number of x :1
Chars other than x: 2


xyxzghz
Total characters in the word: 7
Number of x :2
Chars other than x: 5


zyxzz
Total characters in the word: 5
Number of x :1
Chars other than x: 4

最佳答案

根据需要工作代码-->

public class Test {
public static void main(String[] args) {

int count1=0;
int chars_not_x=0 ;

String str = "xyz xyxzghz zyxzz";
String[] words = str.split("\\s");

for(int m=0; m<words.length; m++){

count1 = 0;    // Add this

System.out.println(words[m]);

System.out.println("Total characters in the word: "+words[m].length());
for(int n=0; n<words[m].length(); n++){
if(words[m].charAt(n)=='x'){count1++;}}

       System.out.println("Number of x :"+count1);
       chars_not_x= words[m].length()- count1; 
       System.out.println("Chars other than x: "+chars_not_x);
       System.out.println("\n");


}} }

关于java - 分别分析字符串的每个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23927618/

相关文章:

java - session 值不显示在 jsp struts 2 中

java - 创建具有不同目标对象的方法引用列表?

java - 将字节数组转换为字符串,字符串传输后无法转换回来

c++ - 如何填充二维字符数组? C++

r - 检查变量是否具有值 ''

java - 以编程方式控制应用程序服务器

java - Hibernate错误: Invocation of init method failed; nested exception is org. hibernate.boot.archive.spi.ArchiveException:无法构建ClassFile

java - 类加载相关的war部署错误

python - 在 python 中的一组字符串中查找超字符串

Python: '_io.TextIOWrapper' 类型的对象没有 len()