简体   繁体   English

在Java中,如何检查字符串是否以相同的方式开始和结束?

[英]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. 我正在学习Java,并且正在完成一些任务。

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 例如,我尝试使用java endsWith和startsWith,但是使用了“ edited”(以“ ed”开头和结尾),但是我一直收到错误消息

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

Yeilds 耶尔德

Error: incompatible types required: java.lang.String found: boolean 错误:要求的类型不兼容:找到的java.lang.String:布尔值

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 :) 不需要时,您将调用startsWith您知道它以定义的开头两个字符开头:)

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. 我假设您已经知道字符串的长度为2或更大...如果不是,则应首先检查该字符串。 (And change the variable valid to whatever makes sense in your context.) (然后将valid变量更改为在您的上下文中有意义的变量。)

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 ind是您需要检查的索引

    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 并考虑到您现在不仅限于2,您可以给ind任何您喜欢的数字,它将起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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