Substring does not return empty string

Asked

Viewed 37 times

2

I have the following text file called fullResponse

<Sum> [stat]player_ammo_restored  = 3447
<Sum> [stat]player_climb_assists  = 2102
<Sum> [stat]player_climb_coops  = 2612
<Sum> [stat]player_damage  = 25129585

There are more lines, this is the beginning of the file. I need to make a substring to get the data. Doing

   val player_ammo_restored = fullResponse
       .substringAfter("<Sum> [stat]player_ammo_restored  = ")
       .substringBefore("\n<Sum>").toInt()

It works, and it brings the value 3447. But if for example, if the line <Sum> [stat]player_climb_assists = 2102 not exist and I try to do

val player_climb_assists  = fullResponse
    .substringAfter("<Sum> [stat]player_climb_assists  = ")
    .substringBefore("\n<Sum>").toInt()

it returns the first line of the file and gives error in converting to int pq instead of bringing the value it brings the full line (<Sum> [stat]player_ammo_restored = 3447)

How do the substring bring an empty string if there is no line I am searching for?

1 answer

2


According to the documentation, the method substringAfter takes as second parameter the string to be returned if the delimiter is not found (and if this parameter is not passed, it returns the string itself).

So you’d just do something like:

val tmp = fullResponse.substringAfter("<Sum> [stat]player_climb_assists  = ", "")

if (tmp.isEmpty()) {
    print("Não tem player_climb_assists")
} else {
    val player_climb_assists = tmp.substringBefore("\n<Sum>").toInt()
    print(player_climb_assists)
}

That is to say, .substringAfter("<Sum> [stat]player_climb_assists = ", "") returns an empty string if the string " [stat] etc..." is not found.

Then just check if it was actually returned empty (because I understood that in this case there is no value to be converted to number), and only if it is not empty, then you proceed and look for the number.


That said, I think an easier way is to read the file and process it line by line. Something like this:

File("fullResponse").forEachLine {
    val valor = it.split("= ")[1].toInt()
    if (it.startsWith("<Sum> [stat]player_ammo_restored")) {
        val player_ammo_restored = valor
        // usar o player_ammo_restored...
    } else if (it.startsWith("<Sum> [stat]player_climb_assists")) {
        val player_climb_assists = valor
        // usar o player_climb_assists...
    } else etc...
}

I find this approach better because you don’t need to load the entire contents of the file at once, in a single string. And also because the other method might fail if you want to take the value of the last line (since there won’t be one \n<Sum> then substringBefore will return the number followed by the line break if the file ends with a).

  • perfect, it was just that

Browser other questions tagged

You are not signed in. Login or sign up in order to post.