#characters after .contains
13 messages · Page 1 of 1 (latest)
Hey, @worldly cliff!
Please remember to /close this post once your question has been answered!
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.
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?
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
public static String getstring(String s,String containing) {
String retrn = "";
char[] chararray = s.toCharArray();
int start = s.lastIndexOf(containing);
if(start = -1) {
//it doesnt contain
}
for(int i = 0;i<s.length();i++) {
Character car = chararray[i];
if(!Character.isDigit(car)) {
retrn+=car;
}
}
return retrn;
}
``` it not best solution but maybe good for understanding
if u want to stop after charecter is digit then add else {break;}
just a little thing to add to that. String concatenation in a loop should be avoided if possible. Have a look at StringBuilder.
oh why tho is there any reason? idk how we can add to strings i thought they were not permutable
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.
ok thx