简体   繁体   中英

How do I split this string back into a list? Using kotlin

I am saving a list of strings to save to shared preferences but as I must save the list as a string, I am really struggling to split the string back into the list. My Strings:

"Wellington, NZ"
"Sydney, AU"
"Melbourne, AU"

I save this in shared preferences as "Wellington, NZ, Sydney, AU, Melbourne AU" How can i split the string back to a list? I cant use string.split(",") as it'll split at every "," and I have also tried using regex bug have had no luck.

given my string in shared preferences is:

val stringToSplit = "Wellington, NZ, Sydney, AU, Melbourne AU"

I need to split this back into a list that looks like this:

val listOfPlaces = ["Wellington, NZ",
                    "Sydney, AU",
                    "Melbourne, AU"]

I think the easiest way would be to append a new string that combines the previous ie:

string1= "Washington, WA"
string2= "Alaska, AK"
string3= "Montana, MT"
string4 = []
string4.append(string1)
string4.append(string2)
string4.append(string3)

print(string4)

which prints:

['Washington, WA', 'Alaska, AK', 'Montana, MT']

You could split them first too if you need the city and state as their own elements.

Please try this:

val s = "a,b,c,d,e"
List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")))

you will get the list of string

You can use chuncked with split to achieve that

val stringToSplit = "Wellington, NZ, Sydney, AU, Melbourne AU"
val splits = stringToSplit.split(",")
val result = splits.chunked(splits.size / 2).map { it.joinToString(",") }
result.forEach { print(it) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM