Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Delete duplicate String?

Status
Not open for further replies.

wangdong

Programmer
Oct 28, 2004
202
CN
Hi, I have a program that allows user to input a string from console. Then the program will delete all the duplicated words. Something like?

if user input: apple plane pen school plane
the system will return: apple plane pen school

I wrote a program to do this? All seems alright, but couldn't get a correct output? can anyone have a look?

Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class DeleteDup {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		String line;
		ArrayList words = new ArrayList();
		String word;
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		line = br.readLine();
		StringTokenizer st = new StringTokenizer(line);
		words.add(st.nextToken());
		while(st.hasMoreTokens()){
			word=st.nextToken();
			for(int i=0;i<words.size();i++){
				if(words.get(i).equals(word)==false){
					words.add(word);
					break;
				}
			}
		}
		for(int i=0;i<words.size();i++){
			System.out.println(words.get(i));
		}
	}

}

Chinese Java Faq Forum
 
You're adding a new word just if it ins't equal to the first one. You should compare it to all the previously added ones.

Anyway, why all that stuff when Java can do it for you?

Code:
// Read the file and stuff

HashSet words = new HashSet();
StringTokenizer tk = new StringTokenizer(line);
while (tk.hasMoreTokens())
   words.add(tk.nextToken());

HassSet class will eliminate duplicate values ... and that's all folks.

Cheers,
Dian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top