简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM