Batakj
Batakj

Reputation: 12743

how to check whether the string ends with exact string?

The input is XYZ

The String array contains three string i.e.

  1. test.alpha.beta.XYZWorld
  2. test.gamaa.mu.XYZ
  3. test.nu.tera.XYZ

I need the last two result if i provide the input "XYZ". Not the test.alpha.beta.XYZWorld. if i use lastIndexOf method defined in java.lang.String, obviously it returns 1,2 and 3 result.

Please help.

Upvotes: 2

Views: 584

Answers (3)

PermGenError
PermGenError

Reputation: 46408

check out String.endsWith(suffix) method from String API. it returns a boolean value.

  String s = "test.gamaa.mu.XYZ";
  System.out.println(s.endsWith("XYZ"));

  returns TRUE

Upvotes: 2

dreambit.io dreambitio
dreambit.io dreambitio

Reputation: 1902

    String pattern = "xyz";
    String a = "xyz";
    String b = "xyzA";

    int position = b.lastIndexOf(pattern);
    if (b.length() == position + pattern.length())
    {
       System.out.print("OK");
    } else
    {
        //error
    }

Upvotes: 2

Dan D.
Dan D.

Reputation: 32391

There is an endsWith() method in String.

Upvotes: 5

Related Questions