#characters after .contains

13 messages · Page 1 of 1 (latest)

worldly cliff
#

How can I check if a string has something in it, .contains("something") and if it does, get x amount of characters after that thing?

velvet kindleBOT
#

Hey, @worldly cliff!
Please remember to /close this post once your question has been answered!

cold rose
#

If you look at the source code of contains the method simply refers to String#indexOf which returns the index of the first occurrence of the specified substring. To get the remaining characters of the String after the first occurrence you can do
lengthOfInitialString - indexOfSubstring - lengthOfSubstring

#

This only works if you want the characters after the first occurrence of the substring not the last.

worldly cliff
#

ah, I see, is there a way I can do this and get every character after it as long as the next character is a number?

cold rose
#

then I would resort to using String#substring. You start at the index of the first occurrence + the length of the substring you searched for. Convert that substring to a char Array and use Character#isDigit to check each character in a for loop. For each character that is a digit you can concatenate it to another String which will then be your result

warm obsidian
#

if u want to stop after charecter is digit then add else {break;}

cold rose
#

just a little thing to add to that. String concatenation in a loop should be avoided if possible. Have a look at StringBuilder.

warm obsidian
#

oh why tho is there any reason? idk how we can add to strings i thought they were not permutable

cold rose
#

yes you are correct they are immutable. That is the reason why manual String concatenation is considered bad practice in a for loop because it creates unnecessary overhead.

worldly cliff
#

ok thx