java - How to count same words in a string and get the index of the first word that is equal? -
my task create static method named "dupwords" gets strings parameter , returns how many times word @ same string. catch is, need return two-dimensional array, have 2 columns , rows how many different sub strings in string...
for example: "abcd xyz abcd abcd def xyz"
this pairs [0][3] [5][2] [19][01] first pair means word "abcd" appears 3 times , state @ index 0 (and rest..)
this image of two-dimensional array: (the text in hebrew can see drawing)
i started something...you think way off :/ (its start) think didn't understand how deal two-dimensional array..
public static int[][] dupwords (string str) { string [] stringarray = str.split(" "); int countwords = 0; int index = 0; int [][] retarr; (int = 0; < stringarray.length; i++) { (int j = 0; j < stringarray.length; j++) { if (stringarray[i].equalsignorecase(stringarray[j])){ countwords++; index = stringarray[i].indexof(str); } } } }
please help, thankss
find number of unique words.
you can it, putting words stringarray
hashmap. hashmap come handy later.
create array retarr = new int[unique][2];
complete solution below (beware, didn't compile it!)
public static int[][] dupwords (string str) { string [] stringarray = str.split(" "); int countwords = 0; int index = 0; hashmap<string, integer> indexmap = new hashmap<string, integer>(); hashmap<string, integer> countmap = new hashmap<string, integer>(); int index = 0; (int = 0; < stringarray.size(); i++) { string s = stringarray[i]; if (!indexmap .containskey(s)) { indexmap.put(s, index); countmap.put(s, 1); } else { int cnt = countmap.get(s); countmap.put(s, cnt+1); } index += s.length() + 1; } int [][] retarr = new int[map.size()][2]; (int = 0; < stringarray.size(); i++) { string s = stringarray[i]; retarr[i][0] = indexmap.get(s); retarr[i][1] = countmap.get(s); } return retarr; }
now, without hashmap, or other dynamic structure it's quite difficult do. easiest approach create bigger necessary array , @ end trim it. this.
public static int[][] dupwords (string str) { string [] stringarray = str.split(" "); int countwords = 0; int index = 0; int [][] retarr = new int[stringarray.size()][2]; int uniqewords = 0; (int = 0; < stringarray.size(); i++) { string s = stringarray[i]; if (s != null) { retarr[uniquewords][0] = str.indexof(s); int cnt = 1; (int j = + 1; j < stringarray.size(); j++) { if (s.equalsignorecase(stringarray[j])) { stringarray[j] = null; cnt++; } } retarr[uniquewords][1] = cnt; uniquewords++; } } int[][] newretarr = new int[uniquewords][2]; (int = 0; < uniquewords; i++) { newretarr[i][0] = retarr[i][0]; newretarr[i][1] = retarr[i][1]; } return newretarr; }
Comments
Post a Comment