Search code examples
javaandroidstringspeech-to-text

Java - Get first letter of string


I am trying to extract the first letters of each word in a sentence the user has spoken into my app. Currently if the user speaks "Hello World 2015" it inserts that into the text field. I wish to split this so if the user speaks "Hello World 2015" only "HW2015" is inserted into the text field.

final ArrayList<String> matches = data.getStringArrayListExtra(
                RecognizerIntent.EXTRA_RESULTS);

The matches variable is storing the users input in an array.I have looked into using split but not sure exactly how this works.

How would I achieve this?

Thank You


Solution

  • You can split a string into an array of string by doing this:

    String[] result = my_string.split("\\s+");  // This is a regex for matching spaces
    

    You could then loop over your array, taking the first character of each string:

    // The string we'll create
    String abbrev = "";
    
    // Loop over the results from the string splitting
    for (int i = 0; i < result.length; i++){
    
        // Grab the first character of this entry
        char c = result[i].charAt(0);
    
        // If its a number, add the whole number
        if (c >= '0' && c <= '9'){
            abbrev += result[i];
        }
    
        // If its not a number, just append the character
        else{
            abbrev += c;
        }
    }