Java,字符串数组。检查文本的第一个和最后一个字母是否相同。我需要用普通快递

Java,字符串数组。检查文本的第一个和最后一个字母是否相同。我需要用普通快递,java,regex,string,algorithm,Java,Regex,String,Algorithm,我有一些文本,我把单词分开,现在我需要检查每个单词是否以相同的字母开头(例如:'teeet','teeet','teeet')。我该怎么做?以下是我所做的: Scanner input = new Scanner(System.in); String text = input.nextLine(); String[] arr = text.split(" "); System.out.println("Display all words in a string:

我有一些文本,我把单词分开,现在我需要检查每个单词是否以相同的字母开头(例如:'teeet','teeet','teeet')。我该怎么做?以下是我所做的:

    Scanner input = new Scanner(System.in);
    String text = input.nextLine();

    String[] arr = text.split(" ");
    System.out.println("Display all words in a string: ");
    for ( String ss : arr) {

        // What now ?
    }
我需要在正则表达式中执行此操作,您可以使用和:

现在比较一下

我建议你在提问之前一定要检查答案,它会包含像这样的问题的答案


有关您的编辑,请参见@Bohemian:

您可以使用正则表达式确定第一个和最后一个字符是否为 相同:

str.matches(“().\\1”)

使用正则表达式:

if (str.matches("(?i)(.).*\\1"))
导入java.util.Scanner

public class Test {

public static void main(String[] args) {
    new Test();
}

public Test() {
    Scanner input = new Scanner(System.in);
    String text = input.nextLine();

    String[] arr = text.split(" ");
    System.out.println("Display all words in a string: ");
    for (String ss : arr) {
        System.out.println("testing word:" + ss);
        String firstLetter = ss.substring(0, 1);
        String lastLetter = ss.substring(ss.length() - 1, ss.length());
        boolean firstEqualsLast = firstLetter.equalsIgnoreCase(lastLetter);
        System.out.println("first char equals last char=" + firstEqualsLast);
    }
}
}

如果您使用
next()
,扫描仪已经按空格分割,但是如果第一个字母是大写字母,最后一个字母是小写字母,我该怎么做呢?那么“Teeet”和“Teeet”也是真的吗?我已经在regex中添加了“ignore case”开关
(?I)
,它现在可以根据需要工作了。
if (str.matches("(?i)(.).*\\1"))
package test;
public class Test {

public static void main(String[] args) {
    new Test();
}

public Test() {
    Scanner input = new Scanner(System.in);
    String text = input.nextLine();

    String[] arr = text.split(" ");
    System.out.println("Display all words in a string: ");
    for (String ss : arr) {
        System.out.println("testing word:" + ss);
        String firstLetter = ss.substring(0, 1);
        String lastLetter = ss.substring(ss.length() - 1, ss.length());
        boolean firstEqualsLast = firstLetter.equalsIgnoreCase(lastLetter);
        System.out.println("first char equals last char=" + firstEqualsLast);
    }
}
}