Java – extract the first letter from each word in the sentence
•
Java
I have developed a voice to text program where users can say a short sentence and insert it into a text box
How do I extract the first letter of each word and insert it into the text field?
For example, if the user says, "Hello world." I want to insert HW in the text box
Solution
If you have a string, you can use it to split it
input.split(" ") //splitting by space //maybe you want to replace dots,etc with nothing).
Iteration array:
for(String s : input.split(" "))
Then get the first letter of each string in the list / array / etc or append it to the string:
//Outside the for-loop: String firstLetters = ""; // Insdie the for-loop: firstLetters = s.charAt(0);
The resulting functions:
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; }
If you want to use a list (ArrayList matching), generate the function:
Basically, you only use array / list / and so on as the parameter type instead of text Split ("") you only need to use parameters In addition, delete the line where you want to replace characters such as dots
public String getFirstLetters(ArrayList<String> text) { String firstLetters = ""; for(String s : text) { firstLetters += s.charAt(0); } return firstLetters; }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码