-3

I have some text , i separated the words and now I need to check each word if it starts with the same letter it ends ( example: 'teeet','teeeT,'Teeet'). How do i do that ? Here is what I've done:

    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 ?
    }

I need to do it in regular expression

ST3
  • 8,826
  • 3
  • 68
  • 92
user2706783
  • 27
  • 2
  • 7

4 Answers4

4

You can use String#charAt and String#length:

char first = ss.charAt(0);
char last  = ss.charAt(ss.length() - 1);

Now compare them.

I recommend you to always check the docs before asking, it will contain the answer for questions like this.


For your edit, see this answer by @Bohemian:

you can determine using regex if the first and last characters are the same:

str.matches("(.).*\\1")

Community
  • 1
  • 1
Maroun
  • 94,125
  • 30
  • 188
  • 241
3
if (ss.charAt(0) == ss.charAt(s.length() - 1)) {
    // Do your stuff
}
ssantos
  • 16,001
  • 7
  • 50
  • 70
2

Use regex:

if (str.matches("(?i)(.).*\\1"))
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • But how do I do the same but if the first letter is uppercase and last is lowercase ? So 'Teeet' and 'teeeT' would also be true ? – user2706783 Oct 13 '13 at 14:12
  • I've added the "ignore case" switch `(?i)` to the regex - it will work as you need now. – Bohemian Oct 13 '13 at 14:13
0
package test;

import 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);
    }
}
}
Michael Besteck
  • 2,415
  • 18
  • 10