简体   繁体   English

打印句子中每个单词的首字母

[英]Print the first letter of each word of a sentence

I need to extract the first character from each word present in the sentence. 我需要从句子中出现的每个单词中提取第一个字符。
the output should be : JaJwuth but it coming : JJJJJaaaaJJJJJwwwwwuuutttthhhhh 输出应为:JaJwuth,但输出为:JJJJJaaaaJJJJJwwwwwuuutttthhhhh

Here is my code: 这是我的代码:

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

        String s = "Jack and Jill went up the hill";
        s = ' ' + s; /* adding space before the string */
        char ch;
        int i, l;
        l = s.length();
        for (i = 0; i < l; i++) {
            if (s.charAt(i) == (' '))
                ch = s.charAt(i + 1);
        }
        System.out.println(ch); /* here the error appears */
    }
}

Please help me understand what I did wrongly, thanks.the output should be:JaJwuth 请帮助我理解我做错了什么,谢谢。输出应该是:JaJwuth

You have to initialize ch 您必须初始化ch

change 更改

char ch;

to

char ch=' ' ;

Other than the initialization problem that you are getting for char ch; 除了要获取的初始化问题以外,其他都没有char ch; , which you fix by initializing it with an empty char ( char ch = ' '; ), this is probably what you are trying to do (without using char ch): ,您可以通过使用空字符( char ch = ' '; )对其进行初始化来解决,这可能是您要尝试执行的操作(不使用char ch):

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

        String s = "Jack and Jill went up the hill";
        s = ' ' + s; /* adding space before the string */
        int strLen = s.length();
        for (int i = 0; i < strLen; i++) {
            if (s.charAt(i) == (' '))
                System.out.println(s.charAt(i + 1));
        }
    }
}

Output: 输出:

J
a
J
w
u
t
h

Note: The System.out.println(...) was outside the for loop in the question. 注意: System.out.println(...)在问题的for循环之外。

您想初始化ch因为在实例中for循环未运行(例如,当i> = 1时),则ch将永远不会初始化,然后您尝试打印出未初始化的变量

char ch ='\0';

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

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