Reputation:
I have a list of elements, the first element is a name city and second information is about thecity. I want read the file cities.txt and put the information of the list in the hashMap. In the file cities.txt the cities and the elements is separate for one tab. But when i put the pieces in the hashMap the second pieces isn't save.
private fun readFile() {
var cityToDefn = java.util.HashMap<String, String>()
val cities = ArrayList<String>()
val reader = Scanner(resources.openRawResource(R.raw.cities))
while (reader.hasNextLine()) {
val line = reader.nextLine()
var pieces = line.split("\\s".toRegex())
if (pieces.size >= 2) {
cities.add(pieces[0])
cityToDefn.put(pieces[0], pieces[1])
}
}
}
cities.txt
lisboa castelo de são jorge
porto torre dos clerigos
aveiro ria
lisboa terreiro do paço
porto avenida dos aliados
lisboa marques de pombal
aveiro igreja da glória
Upvotes: 1
Views: 43
Reputation: 93629
You say there's a tab after the cities, but in your example it looks like multiple spaces. So you can use \\s+
to split on the first group of white space. And add a limit of two, so the description is not broken up:
var pieces = line.split("\\s+".toRegex(), 2)
What if there are cities with two-word names? Then I think you really need a tab after the city name, and you could split on a tab character, without regex:
var pieces = line.split('\t')
Upvotes: 1
Reputation: 2039
Try to use Kotlin's classes when you operate with Kotlin.
This would solve the problem:
private fun readFile() {
val cityToDefn = mutableMapOf<String,String>()
val reader = Scanner(resources.openRawResource(R.raw.cities))
while (reader.hasNextLine()) {
val line = reader.nextLine()
val left = msg.substringBefore(' ')
val right = msg.substringAfter(' ')
cityToDefn[left] = right
}
val cities = cityToDefn.keys
}
BTW: The right
String will sometimes have some spaces in front, so you maybe want to filter them out.
Upvotes: 0