获取字符串中每个单词的第一个字符 [英] Get the first character of each word in a String

查看:59
本文介绍了获取字符串中每个单词的第一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使程序执行以下操作:

I am trying to get a program working which does the following:

假设我们有一个名为 name String ,设置为"Stack Overflow Exchange" .我想将每个单词的第一个字符输出到用户"SOE" .我尝试使用 split()方法,但没有成功.

Let's say we have a String called name, set to "Stack Overflow Exchange". I want to output to the user "SOE", with the first characters of each word. I tried with the split() method, but I failed to do it.

我的代码:

public class q4 {
    public static void main(String args[]) {
        String x = "michele jones";
        String[] myName = x.split("");
        for(int i = 0; i < myName.length; i++) {
            if(myName[i] == "") {
                String s = myName[i];
                System.out.println(s);
            }              
        }         
    }     
}   

我试图检测是否有空格,那么我可以简单地获取下一个索引.谁能告诉我我在做什么错?

I am trying to detect if there are any spaces, then I can simply take the next index. Could anyone tell me what I am doing wrong?

推荐答案

尝试按" (空格)进行拆分,然后获取 charAt(0)(第一个字符)),然后像这样打印:

Try splitting by " " (space), then getting the charAt(0) (first character) of each word and printing it like this:

public static void main(String args[]) {
    String x = "Shojibur rahman";
    String[] myName = x.split(" ");
    for (int i = 0; i < myName.length; i++) {
        String s = myName[i];
        System.out.println(s.charAt(0));
    }
}

这篇关于获取字符串中每个单词的第一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆