HasDuplicates.javaFrom WikiJava
This example gets from command line a
the article
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 important methods used here are:
hasDuplicates.javapackage 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; } } |
