sanghvi
sanghvi

Reputation: 43

How to print the first recurring character in a string?

I got a school assignment that I have to create a program that prints the first recurring character in a given string.

For example, if the input is "helloo", then it should output as "l". I wrote the following code but it prints "l" and "o" both.

String text = "helloo";
int length = text.length();
for (int i = 0; i <= length - 1; i++) {
 char curChar = text.charAt(i);
 for (int j = i + 1; j <= length - 1; j++) {
  if (curChar == text.charAt(j)) {
   System.out.println(curChar);
   break;
  }
 }
}

Can someone help me out with this? Thanks for any answers!

Upvotes: 4

Views: 201

Answers (4)

Tanay U
Tanay U

Reputation: 1

        class FirstRepeatingChar
        {
        public static void main(String args[])
        {

         String s="hello";
          for(int i=0;i<s.length();i++)
          {
           for(int j=0;j<s.length();j++)
            { 
              if(s.charAt(i)==s.charAt(j))
                { 
System.out.println("  the First non repeating character is "  +s.charAt(i));
                 break;
                }
             }
           }
         }
         }

Upvotes: 0

Wraith
Wraith

Reputation: 296

You're breaking just the inner loop but not the outer loop. You can use break with a label for the outer loop. For example:

String text = "helloo";
int length = text.length();
outerloop:
for (int i = 0; i <= length - 1; i++) {
    char curChar = text.charAt(i);
    for (int j = i + 1; j <= length - 1; j++) {
        if (curChar == text.charAt(j)) {
            System.out.println(curChar);
            break outerloop;
        }
    }
}

Get more information here - How to break out of nested loops in Java?

Hope this helps, but you should try doing your school assignments yourself.

Upvotes: 3

Cedric
Cedric

Reputation: 19

Here's another variant:

 String text = "helloo";
    ArrayList<String> a = new ArrayList<String>(Arrays.asList(text.split(Pattern.quote(""))));
    for(int i = 0; i < a.size()-1;i++) {
        if(a.get(i).compareTo(a.get(i+1)) == 0) {
            System.out.println(a.get(i));
            break;
    }

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522007

I realize that you are asking for a direct fix to your current approach. But for those who might read this question in the future, there is a very sleek approach here using regular expressions:

String text = "helloo";
String match = text.replaceAll("^.*?(.)\\1.*", "$1");
System.out.println(match);

l

Demo

The basic idea of the pattern ^.*?(.)\1 is to consume the least number of characters in the string until we hit a single character which is followed by that same character.

Upvotes: 0

Related Questions