Reputation: 109
how to split the string shown below and assign it to 4 different variables like name, price, image, and quantity
Upvotes: 0
Views: 862
Reputation: 23
I know this is very late to the game, but what you want to do can be done. However, probably not as cleanly as you would hope. You can, as previously stated, split your string into an array and then create variables using that array as follows (I added code to remove the curly braces too).
final list = str.replaceFirst('}', '', str.length - 1).replaceFirst('{', '').split(',');
final String name = list[0], price = list[1], image = list[2], quantity = list[3];
Of course, this assumes that each string entry contains four items. If it contains fewer than four, you will receive a RangeError
exception.
Upvotes: 0
Reputation: 29
String [ ] str = Any_String.split(" , ")
// Whatever u will give inside those brrackets , string will be splitted based on that. In this case the splitter is ,
str will be a list , and u can get its values using its index[ ]
Upvotes: 1