Java 获取字符串中每个单词的第一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26180992/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:58:31  来源:igfitidea点击:

Get the first character of each word in a String

javastring

提问by farhana konka

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

我正在尝试让一个程序运行,它执行以下操作:

Let's say we have a Stringcalled 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.

假设我们有一个String被调用的name,设置为"Stack Overflow Exchange"。我想输出给 user "SOE",每个单词的第一个字符。我尝试了该split()方法,但没有成功。

My code:

我的代码:

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?

我试图检测是否有任何空格,然后我可以简单地取下一个索引。谁能告诉我我做错了什么?

采纳答案by brso05

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

尝试按" "(空格)分割,然后获取charAt(0)每个单词的(第一个字符)并像这样打印:

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));
    }
}

回答by Simone Gianni

String initials = "";
for (String s : fullname.split(" ")) {
  initials+=s.charAt(0);
}
System.out.println(initials);

This works this way :

这是这样工作的:

  1. Declare a variable "initials" to hold the result
  2. Split the fullname string on space, and iterate on the single words
  3. Add to initials the first character of each word
  1. 声明一个变量“initials”来保存结果
  2. 在空格上拆分全名字符串,并迭代单个单词
  3. 将每个单词的第一个字符添加到首字母

EDIT :

编辑 :

As suggested, string concatenation is often not efficient, and StringBuilder is a better alternative if you are working on very long strings :

正如所建议的那样,字符串连接通常效率不高,如果您正在处理很长的字符串,则 StringBuilder 是更好的选择:

StringBuilder initials = new StringBuilder();
for (String s : fullname.split(" ")) {
  initials.append(s.charAt(0));
}
System.out.println(initials.toString());

EDIT :

编辑 :

You can obtain a String as an array of characters simply :

您可以简单地将字符串作为字符数组获取:

char[] characters = initials.toString().toCharArray();

回答by StackFlowed

You need to spilt it with a space you cannot split with "". It doesn't mean anything. Another thing you did wrong was === in string comparison that is not correct. Please refer to How do I compare strings in Java?

你需要用一个你不能用“”分割的空间来溢出它。这不代表什么。你做错的另一件事是在字符串比较中 === 不正确。请参阅如何比较 Java 中的字符串?

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

回答by Jesper

There are a number of errors in your code:

您的代码中有许多错误:

String [] myName=x.split("");

Did you really want to split on ""(empty string)? You probably wanted to split on spaces:

你真的想拆分""(空字符串)吗?您可能想在空格上拆分:

String [] myName=x.split(" ");

And:

和:

if(myName[i]=="")

Never compare strings with ==in Java, always use .equals:

永远不要将字符串与==Java 中的字符串进行比较,始终使用.equals

if (myName[i].equals(""))

回答by Tim B

You are splitting on an empty string not a space " ". Your loops don't really make much sense either, I'm not sure what you are trying to do.

您正在拆分空字符串而不是空格“”。您的循环也没有多大意义,我不确定您要做什么。

   String [] myName=x.split(" ");
   for(int i=0; i<myName.length; i++)
   {
       if (!myName[i].isEmpty()) {
          System.out.println(myName[i].charAt(0));
       }              
   }          

回答by Jake Huang

Since you don't have thread-safe with your program, you could use StringBuilder. For the long string, i recommand you could use StringTokenizer.

由于您的程序没有线程安全,因此您可以使用StringBuilder. 对于长字符串,我建议您可以使用StringTokenizer.

回答by Jeffrey Bosboom

With Java 8 streams:

使用 Java 8 流:

String initials = Arrays.stream(str.split(" "))
    .map(s -> s.substring(0, 1))
    .collect(Collectors.joining());
System.out.println(initials);

回答by Marco Tulio Avila Cerón

The accepted reply in Java 8:

Java 8 中接受的回复:

/**
 * Gets the first character of every word in the sentence.
 *
 * @param string
 * @return
 */
public static String getFirstLetterFromEachWordInSentence(final String string) {
    if (string == null) {
        return null;
    }
    StringBuilder sb = new StringBuilder();
    Arrays.asList(string.split(" ")).forEach(s -> sb.append(s.charAt(0)).append(" "));
    return sb.toString().trim();
}

回答by Prashant Jajal

If you are using kotlin then you can use below code for get initial charactor

如果您使用的是 kotlin,则可以使用以下代码获取初始字符

 val myName = name.split(" ")
 val initial = myName.fold("", { acc, s -> acc + s[0] })
 print(initial)

回答by Lokesh

Surprised that nobody mentioned about making use of an already available library. One can use here WordUtilsform apache commons-text

令人惊讶的是,没有人提到使用已经可用的库。可以在这里使用WordUtils表单 apachecommons-text

String name = "My Name";
String initials = WordUtils.initials(name);
System.out.println(initials);  // Outputs:  MN