2015-02-11 138 views
3

我已經開發了一個語音文本程序,用戶可以說一個簡短的句子,然後將其插入文本框中。提取句子中每個單詞的第一個字母

如何提取每個單詞的第一個字母,然後將其插入文本字段?

例如,如果用戶說:「Hello World」。我想插入HW到文本框中。

+0

這個關於語音識別的問題,還是你已經有了包含用戶說的字符串? – immibis 2015-02-11 18:34:45

+0

用戶說出和內容被存儲到一個字符串 如果(requestCode == RECOGNIZER_RESULT && resultCode爲== RESULT_OK){ 最終的ArrayList 匹配= data.getStringArrayListExtra( RecognizerIntent.EXTRA_RESULTS); 匹配是存儲輸入的字符串 – BasicCoder 2015-02-11 18:36:17

+0

查看字符串API。有很多方法可以像'charAt','split','substring'一樣使用。嘗試一下,什麼時候它不起作用回來你的嘗試。 – Pshemo 2015-02-11 18:36:38

回答

0

使用split來獲得一個數組分隔的單詞,那麼你可以得到前012個N個字符與substring(0,N)。

6

如果你有一個字符串,你可以使用

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; 
} 
+2

你測試過你的例子嗎? (1)字符串是不可變的(2)你會爲'replaceAll(「。」,「」)'做什麼感到驚訝 – Pshemo 2015-02-11 18:54:23

+0

啊是的,不,我沒有。忘了轉義點,謝謝提醒! – Cyphrags 2015-02-11 18:57:38

+0

text = text.replaceAll(「\\。」,「」).replaceAll(「,」,「」); – prime 2015-02-11 18:58:27

-1

你想通過

String[] old = myTextView.getText().split(" "); 
String add=""; 
for(String s:old) 
    add+=""+s.charAt(0); 
myTextView.setText(add); 
+0

什麼是'myList'? – prime 2015-02-11 19:20:08

+0

我的不好,我的意思是老 – Zach 2015-02-11 23:20:08

0

提取字符串,把它全部放入一個列表和循環假設句只包含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)); 
+0

我試了我的代碼 String input = matches.toString(); StringBuilder sb = new StringBuilder();對於(String s:input.split(「」)){ sb.append(s.charAt(0)); } 它沒有工作 - 匹配是存儲輸入的字符串。輸出只是整句 – BasicCoder 2015-02-11 19:22:20

+0

嘗試'String input = matches;' – prime 2015-02-11 19:37:48

+0

什麼是'matches'字符串?你可以把它粘貼在這裏還是在問題中? – prime 2015-02-11 19:41:02

相關問題