I have a String with different value every time:
String words = "My name is Rob Joe";
I want to get only last word
Joe
but every time I don't know how many words the string consists of
CodePudding user response:
In Flutter(Dart), you can get the last word of a string by splitting the string into an array of substrings using the split method and then accessing the last element of the resulting array. Here's an example:
String words = "My name is Rob Joe";
List<String> wordsArray = myString.split(" ");
String lastWord = wordsArray[wordsArray.length - 1];
print(lastWord); // "Joe"
CodePudding user response:
String words = "My name is Rob Joe";
var array = words.split(" "); // <-- [My, name, is, Rob, Joe]
print(array.last); // output 'Joe'
CodePudding user response:
Instead of splitting, you can also use substring
and lastIndexOf
:
final words = "My name is Rob Joe";
final lastWord = words.substring(words.lastIndexOf(" ") 1);
print(lastWord);