Click to See Complete Forum and Search --> : Comparing strings


Rabbit3cat
10-25-2005, 06:02 PM
Hey

Im trying to read an undefined number of strings from a file.
Compare these and output all the strings that are the same, along with the amount of times each string occurs.
ie, for the strings: mountain lava cake mountain lava
the program would return mountain 2, lava 2, cake 1
The way i have approached this, is to read the strings from the file and store them in an array

What im not sure about is how to compare the strings, and return only one of each string, disguarding all the duplicates, then to return the number of times each string appears in the file.

Does anybody know how i could do this??

String thisLine;
int count = 0;

String s[] = new String[10];
try {
FileInputStream fin = new FileInputStream("Recipients");

BufferedReader myInput = new BufferedReader
(new InputStreamReader(fin)); int i = 0;
while (((thisLine=myInput.readLine())!=null)&&i<10) {
//add the strings to the array s
s[i] = thisLine;
System.out.println(s[i]);
count++;
//compare the strings and return all that are the same for(int index = 0; index < s.length; index++) {

for(int index1 = 0; index1 < s.length; index1++){
if((s[index].compareTo(s[index1])) == 0) {
s[index] = s[index1];
//Here i want to for each string the amount of times it occurs

}

}
}

Waylander
10-25-2005, 09:51 PM
What i think would be the way to do this is to store each of the values of the strings and balance the index against a total of how many times the string occurs, then when you read a new string you look in your list of uniques and if you find a match you up the corresponding total, if no match you add the string to the uniques.

However every value you get is going to increase how long each test will take, one thing I will suggest is no to bother reading the file into an initial array, you will be double handling the values, just do the calculation after each line is read using a simple string as a buffer.

Something like this:
(I say like because I cant compile it at the moment best just to use it as an example)



String thisLine;
String strings[] = new String[10];
int amount[] = new int[10];
FileInputStream fin = new FileInputStream("Recipients");
BufferedReader myInput = new BufferedReader(new InputStreamReader(fin));
int i = 0;
int k = 0;

while (((thisLine=myInput.readLine())!=null)&&i<10)
{
while (k<10)
{
if (strings[k].equals(thisLine))
{
amount[k]++;
k=100;
}

if (strings[k].equals(""))
{
strings[k] = thisLine;
amount[k] = 1;
k=100;
}
}
}


Someone else can probably give you a way to link the two arrays (im not not one for linked lists, never really seen thier value) and the amount array will probably have to start with default values of zero im not sure if it does, the way ive set the loop isnt elegant either but it should be enough for a start.

Waylander.

Rabbit3cat
10-26-2005, 05:24 PM
Thanks Waylander, will try that greatly appreciated!

JjavaJ
10-31-2005, 08:26 PM
removed