user3449154
user3449154

Reputation: 19

In Java, how do I check if a string begins and ends the same way?

I'm learning Java, and I'm completing some problems tasked to me.

I've come across a specific problem and I feel like the answer is so simple, but I just can't find it.

I need to check if given string ends with the first two characters it begins with. For example, "edited" (begins and ends with "ed") I've tried using the java endsWith and startsWith, but I keep getting an error

 start = text.startsWith(text.substring(0,2));

Yeilds

Error: incompatible types required: java.lang.String found: boolean

Any help would be appreciated.

Thankyou.

Upvotes: 2

Views: 1425

Answers (2)

Siavosh
Siavosh

Reputation: 2354

This is a dynamic code for what you need to do

let's say we have

    String testak = "tesHJKLtes"
    //index you need to check here 2
    int ind = 2;

ind is the index you need to check

    if ( testak.substring(0,ind).equals(testak.substring(testak.length()
     -ind-1,testak.length()-1))){
        System.out.println("yeeaaahhh");
    }

and consider that this you are not limited to 2 anymore you can give ind any number you like and it will work

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500525

You're calling startsWith when you don't need to - you know it starts with the first two characters, by definition :)

You could have:

String start = text.substring(0, 2);
boolean valid = text.endsWith(start);

Or just collapse the two:

boolean valid = text.endsWith(text.substring(0, 2));

I'm assuming you already know the string is of length 2 or more... if not, you should check that first. (And change the variable valid to whatever makes sense in your context.)

Upvotes: 6

Related Questions