Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the first letter from each word in a sentence

Tags:

java

string

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.

like image 507
BasicCoder Avatar asked Jan 08 '23 22:01

BasicCoder


1 Answers

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):

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.

public String getFirstLetters(ArrayList<String> text)
{
  String firstLetters = "";
  for(String s : text)
  {
    firstLetters += s.charAt(0);
  }
  return firstLetters;
}
like image 128
Cyphrags Avatar answered Jan 17 '23 18:01

Cyphrags