java 从句子中的每个单词中提取第一个字母
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28461821/
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
Extract the first letter from each word in a sentence
提问by BasicCoder
I have developed a speech to text program where the user can speak a short sentence and then inserts that into a text box.
我开发了一个语音转文本程序,用户可以在其中说出一个简短的句子,然后将其插入到文本框中。
How do I extract the first letters of each word and then insert that into the text field?
如何提取每个单词的第一个字母,然后将其插入文本字段?
For example if the user says: "Hello World". I want to insert HW into the text box.
例如,如果用户说:“Hello World”。我想将硬件插入文本框中。
回答by Cyphrags
If you have a string, you could just split it using
如果你有一个字符串,你可以使用
input.split(" ") //splitting by space
//maybe you want to replace dots, etc with nothing).
The iterate over the array:
遍历数组:
for(String s : input.split(" "))
And then get the first letter of every string in a list/array/etc or append it to a string:
然后获取列表/数组/等中每个字符串的第一个字母或将其附加到字符串中:
//Outside the for-loop:
String firstLetters = "";
// Insdie the for-loop:
firstLetters = s.charAt(0);
The resulting function:
结果函数:
public String getFirstLetters(String text)
{
String firstLetters = "";
text = text.replaceAll("[.,]", ""); // Replace dots, etc (optional)
for(String s : text.split(" "))
{
firstLetters += s.charAt(0);
}
return firstLetters;
}
The resulting function if you want to use a list (ArrayList matches):
如果要使用列表(ArrayList 匹配),则生成的函数:
Basically you just use an array/list/etc as argument type and instead of text.split(" ")you just use the argument. Also, remove the line where you would replace characters like dots, etc.
基本上,您只需使用数组/列表/等作为参数类型,而不是text.split(" ")您只需使用参数。此外,删除您将替换点等字符的行。
public String getFirstLetters(ArrayList<String> text)
{
String firstLetters = "";
for(String s : text)
{
firstLetters += s.charAt(0);
}
return firstLetters;
}
回答by Juanjo Vega
回答by Zach
You would want to extract the string, put it all into a list, and loop through
您可能想要提取字符串,将其全部放入列表中,然后循环遍历
String[] old = myTextView.getText().split(" ");
String add="";
for(String s:old)
add+=""+s.charAt(0);
myTextView.setText(add);
回答by prime
Assuming the sentence only contain a-z and A-Z and " " to separate the words
, If you want an efficient way to do it, I suggest the below method.
假设句子只包含a-z and A-Z and " " to separate the words
,如果您想要一种有效的方法,我建议使用以下方法。
public String getResult(String input){
StringBuilder sb = new StringBuilder();
for(String s : input.split(" ")){
sb.append(s.charAt(0));
}
return sb.toString();
}
Then write it to the text field.
然后将其写入文本字段。
jTextField.setText(getResult(input_String));