我已經開發了一個語音文本程序,用戶可以說一個簡短的句子,然後將其插入文本框中。提取句子中每個單詞的第一個字母
如何提取每個單詞的第一個字母,然後將其插入文本字段?
例如,如果用戶說:「Hello World」。我想插入HW到文本框中。
我已經開發了一個語音文本程序,用戶可以說一個簡短的句子,然後將其插入文本框中。提取句子中每個單詞的第一個字母
如何提取每個單詞的第一個字母,然後將其插入文本字段?
例如,如果用戶說:「Hello World」。我想插入HW到文本框中。
如果你有一個字符串,你可以使用
input.split(" ") //splitting by space
//maybe you want to replace dots, etc with nothing).
的迭代這個數組只是把它分解:
for(String s : input.split(" "))
,然後讓每個字符串的第一個字母列表/陣列/等或將其追加到的字符串:
//Outside the for-loop:
String firstLetters = "";
// Insdie the for-loop:
firstLetters = s.charAt(0);
所得功能:
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;
}
如果你想使用的列表(ArrayList的匹配)將所得的函數:
基本上你只需使用一個陣列/列表/等作爲參數類型和代替text.split(「」)你只是使用參數。此外,刪除線,在那裏你將取代像點字符等
public String getFirstLetters(ArrayList<String> text)
{
String firstLetters = "";
for(String s : text)
{
firstLetters += s.charAt(0);
}
return firstLetters;
}
提取字符串,把它全部放入一個列表和循環假設句只包含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();
}
然後將其寫入文本字段。
jTextField.setText(getResult(input_String));
我試了我的代碼 String input = matches.toString(); StringBuilder sb = new StringBuilder();對於(String s:input.split(「」)){ sb.append(s.charAt(0)); } 它沒有工作 - 匹配是存儲輸入的字符串。輸出只是整句 – BasicCoder 2015-02-11 19:22:20
嘗試'String input = matches;' – prime 2015-02-11 19:37:48
什麼是'matches'字符串?你可以把它粘貼在這裏還是在問題中? – prime 2015-02-11 19:41:02
這個關於語音識別的問題,還是你已經有了包含用戶說的字符串? – immibis 2015-02-11 18:34:45
用戶說出和內容被存儲到一個字符串 如果(requestCode == RECOGNIZER_RESULT && resultCode爲== RESULT_OK){ 最終的ArrayList匹配= data.getStringArrayListExtra( RecognizerIntent.EXTRA_RESULTS); 匹配是存儲輸入的字符串 –
BasicCoder
2015-02-11 18:36:17
查看字符串API。有很多方法可以像'charAt','split','substring'一樣使用。嘗試一下,什麼時候它不起作用回來你的嘗試。 – Pshemo 2015-02-11 18:36:38