magicmass
magicmass

Reputation: 89

How to split a String from a list in dart

I'm trying to sort some data in a List<String>. I want to split a long String of every other item and delete part of it. Data will be added to the list when the user performs an action.

Example of what could be in the list:

NOTE* These are not separate items in the list. Its all one String.

"Cat walked across the road"

What I want from this String is just:

"Cat"

Currently, I've initialised the list and split the String as shown below.

//Initialised List
 List<String> list = [];

//Method to split and delete String
String handleString(String items){

//Splits String
    items.split(" ").toString();

//TODO Delete String 

}

Output of this code looks like this:

Cat, walked, across, the, road

The code below gets a single item from the list using .text get method.

for(var txt in list){
     String sentenceInList  = txt.text
print(txt.text);


}

Output :

Cat walked across the road

Im not sure how to remove everything except the first word of every other potential item in the list?

Im looking to start at item one so if the items were as shown below, it would look like this:

Item 1: "Cat walked across the road"

Output: Cat

Item 2: How are you today

How are you today

and so on...

If anyone is able to help with this, it would be most appreciated?

Upvotes: 1

Views: 2558

Answers (1)

Mattia
Mattia

Reputation: 6544

If you need to split your list on your first space character you could just use substring together with indexOf:

var str = 'Cat walked across the road';
var index= str.indexOf(' ');

var cat = str.substring(0, index); // The substring before the space.
var walked = str.substring(index); // The substringafter the space (including it, add +1 to the index to exclude the space).

or if you want to stick with split you can use skip to skip the first element:

var str = 'Cat walked across the road';
var split = str.split(' ');

var the = split.first; // The substring before the space.
var walked = split.skip(1).join(' '); // The substringafter the space.

Upvotes: 3

Related Questions