-3

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

Roksi
  • 9
  • 1

3 Answers3

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));
    }
}
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.