Sunday, 27th June 2010
The new frontier for learning Java

HasDuplicates.java

From WikiJava

Jump to: navigation, search


This example gets from command line a String containing some text and finds if there's any duplicate character in it.

Contents

the article

Image:250px-Subversion.png
You can download the complete code of this article from the Subversion repository at this link

Using the username:readonly and password: readonly

See the using the SVN repository instructions page for more help about this.

The core part of this example is the has duplicate method:

   private static boolean hasDuplicates(String string) {
	for (int i = 0; i < string.length() - 1; i++) {
	    if (string.substring(i + 1).contains(string.subSequence(i, i + 1))) {
		return true;
	    }
	}
	return false;
    }

which contains a for loop to check for each character of the String if the rest of the String contains that character.

There are two simple optimizations in it:

  • The for doesn't check the last character of the string, it's not necessary, since there's no rest of the string
  • the if checks only for duplicates in the string starting from the character following the current character. If in the characters before this there were no duplicates there's no point in checking them again.

The important methods used here are:

  • String java.lang.String.substring(int beginIndex) that returns the end of the string starting at the position beginIndex.
  • boolean java.lang.String.contains(CharSequence s) which checks if the substring, obtained with the previous method, contains one of the characters in the java.lang.CharSequence.
  • CharSequence java.lang.String.subSequence(int beginIndex, int endIndex) which extracts a substring and returns it as a charSequence.

hasDuplicates.java

package org.wikijava.basic;
 
/**
 * @author Giulio
 */
public class hasDuplicates {
 
    /**
     * calls the hasDuplicates Method
     * 
     * @param args
     *            one param, the string to validate for duplicates
     */
    public static void main(String[] args) {
	if (args.length < 1) {
	    System.err.println("usage: hasDuplicates <string>");
	    return;
	}
 
	String string = args[0].trim();
 
	if (hasDuplicates(string)) {
	    System.out.println("there's a duplicate");
	}
	return;
    }
 
    /**
     * 
     * finds if a string contains duplicate characters
     * 
     * @param string
     * @return true if there's a character which is duplicate in the string
     */
    private static boolean hasDuplicates(String string) {
	for (int i = 0; i < string.length() - 1; i++) {
	    if (string.substring(i + 1).contains(string.subSequence(i, i + 1))) {
		return true;
	    }
	}
	return false;
    }
 
}

Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Title (required):

Website:

Comment: