I have to prove if String ends with int, also cases like "Cat 100" or "Cat 1". Is there a way to write it like "Cat "+(int) or do I have to know, which specific number ends String
Asked
Active
Viewed 620 times
-3
-
1Regex works for this. `re.match('Cat \d+$', your_string)` should work – Green Cloak Guy Jan 05 '21 at 18:54
-
Does it also need to start with Cat? Are other characters between Cat and number allowed like `Cat Tom 123` or `Cataclysm 123`? – Pshemo Jan 05 '21 at 18:54
-
See https://stackoverflow.com/a/2620609/2039546 – İsmail Y. Jan 05 '21 at 18:55
-
Including negatives? Is `Cat -1` acceptable? – Dawood ibn Kareem Jan 05 '21 at 19:19
-
nope, only numbers more than 0 – Roksi Jan 06 '21 at 09:49
3 Answers
2
You can use the function isDigit(). Check an example.
import java.lang.Character.*;
public class Main
{
public static boolean lastIsDigit(String s){
char c = s.charAt(s.length() - 1);
return Character.isDigit(c);
}
public static void main(String[] args) {
String a = "Hello World!";
String b = "Hello World1";
System.out.println(lastIsDigit(a));
System.out.println(lastIsDigit(b));
}
}

Kerasiotis Ioannis
- 51
- 1
- 9
0
You can use splint string for this to separate the word "Cat " from the number and then check if the extension is a number, something like this maybe.
String str = "Cat 101";
String[] arrOfStr = str.split(" ");
try {
int number = Integer.parseInt(arrOfStr[1]);
} catch (NumberFormatException nfe) {
System.out.println("The string does not end with an int");
}

deamonLucy
- 205
- 3
- 9
0
You can count characters, assign the value, trim to the one before last. Then make StringToInt and if it is (let's call it x) x = 0 or x > 0 or x < 0 then it was number indeed.

Pantelis Pap.
- 17
- 8