Solved Splitting a String into int's into one sum

Discussion in 'Plugin Development' started by justin1222, Jul 22, 2016.

Thread Status:
Not open for further replies.
  1. Offline

    justin1222

    Can someone please tell me a good way to convert "1 | 2 | 3 | 4" to the sum of all the numbers: 10.
     
  2. Offline

    Zombie_Striker

    @justin1222
    1. Split the string at "|".
    2. Create a for int loop to loop through each sub-string.
    3. Parse each string to an integer
    4. Add all the integers together.
     
  3. Offline

    mine-care

    In adition to what @Zombie_Striker recomended, use the method String#split(String param); to split the string and provide "\\|" as 'param'. This will escape the character '|' which happends to be a regex operator. Then, do as @Zombie_Striker recomended.

    If the numbers are consecutive as shown in the example above, or follow the principles of arithmetic/geometric sequences, you can simply use a formula to calculate the sum rather than running a loop through them, which would be more efficient for large number sets.
     
  4. Offline

    justin1222

    Why is it that if cards = "11 | 11", cards.split("|")[1] = 1?
     
  5. Offline

    Webster56

    You might want to get rid of whitespaces
     
  6. @justin1222
    | is a regex operator (String.split() splits based on regexes). You need to escape it by putting //|. The reason for this is that the regex operator | specifies an alternative pattern to match, and both sides of the | is nothing, so it will just split at every character.
     
  7. Offline

    justin1222

    The plugin needs it that way.

    Please give me an example of this line of code.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.

    Okay, now I have solved the problem. Thank you all for your help!
     
    Last edited: Jul 22, 2016
  8. Offline

    Webster56

    Try cards.split(Pattern.quote("|"));, I've also had issues splitting on the pipe character before.

    And for the whitespaces, remove them after the split, with a trim for instance.
     
Thread Status:
Not open for further replies.

Share This Page