0

I have a large string like "wall hall to wall hall fall be", and I want to print longest strings. Then i want to know how many times all longest strings Is repeated?
For exampele,longest strings are:
wall Is repeated 2
hall Is repeated 2
fall Is repeated 1
This is my code:

public void bigesttstring(String str){
    String[] wordsArray=str.split(" ");
    int n= str.trim().split("\\s+").length;
    int maxsize=0;
    String maxWord="";
    for(int i=0;i<wordsArray.length;i++){
        if(wordsArray[i].length()>maxsize){
             maxWord=wordsArray[i];
             maxsize=wordsArray[i].length();
        }
    }
    System.out.println("Max sized word is "+maxWord+" with  size "+maxsize);
}

But this code only prints "wall".
for count repeated String(i mean "maxWord"),this code write:

int count=0; 
for(int i=0;i<wordsArray.length;i++){
    if(maxWord.equals(wordsArray[i])){
         count++;
    }
}

and for display other longest strings i have this code:

int k=0;
for(int i=0;i<wordsArray.length;i++){
    if(maxWord.equals(wordsArray[i])){
         continue;
    }
    if(maxsize==wordsArray[i].length()){
         k++;
    }
}
String[] other=new String[k];
int o=0;
for(int i=0;i<wordsArray.length;i++){
    if(maxWord.equals(wordsArray[i])){
         continue;
    }
    if(maxsize==wordsArray[i].length()){
         other[o]=wordsArray[i];
         o++;
    }
}  

I allowed to use this functions:

char char At(int i);               
int ComoareTo(String another string);              
boolean endsWith(String suffix);                     
int indexof();                      
int indexof(String str);                       
String substring();
char[] toCharArray();                            
String lowercase();         

And want another code like this for shortest strings.

4 Answers4

0

You have written

  if(wordsArray[i].length()>maxsize)

For wall, hall and fall, it is only true for first wall. That's why you are getting wall and size 4. Here you are not considering that the longest string length may be same for different string. You will have to store the longest string in an array and if condition should be

   if(wordsArray[i].length()>=maxsize)

you will consider = and > case seperately. Since in the case of > you will have to delete all the string in array.

Rahul
  • 3,479
  • 3
  • 16
  • 28
0

You need to change it to equal because currently if the words is the same length as the current largest word it will ignore it. Also if you want it to have the biggest words. You need to store them in an array. I implemented it here.

package OtherPeoplesCode;

public class string {

    public static void main(String[] args) {
        bigeststring("wall hall to wall hall fall be");
    }

    public static void bigeststring(String str){
        String[] wordsArray=str.split(" ");
        String[] biggestWordsArray = new String[wordsArray.length];
        int x = 0;
        int n= str.trim().split("\\s+").length;
        int maxsize=0;
        String maxWord="";
        for(int i=0;i<wordsArray.length;i++){
            if(wordsArray[i].length()>maxsize){
                maxWord=wordsArray[i];
                maxsize=wordsArray[i].length();
                for(int y = 0; y <= biggestWordsArray.length -1; y++){
                    biggestWordsArray[y] = "";
                }
            }
            else if(maxsize==wordsArray[i].length()){
                biggestWordsArray[x] = wordsArray[i];
                x++;
            }
        }
        if(biggestWordsArray[0].equals("")){
            System.out.println("Max sized word is "+maxWord+" with  size "+maxsize);
        }
        else if(!(biggestWordsArray[0].equals(""))){
            System.out.println("TIE!");
            for(int y = 0; y <= biggestWordsArray.length -1; y++){
                if(!(biggestWordsArray[y].equals(""))){
                    System.out.print("Word #" + y + " is ");
                    System.out.println(biggestWordsArray[y]);
                }
            }
        }
    }
}

EDIT: This is the working code, sorry about the delay.

cubecubed
  • 228
  • 4
  • 18
  • @user3359479 I posted an answer, tell me what you think. I believe I achieved what you wished. – cubecubed Feb 28 '14 at 06:40
  • @user335947 I fixed the errors, again, I tested it and it seems to work fine. Sorry about the delay. – cubecubed Feb 28 '14 at 07:04
  • @ Cammy_the_block tnx. It works fine but also i want to know hao many times each lengest words are repeated. Again tnx. – user3359479 Feb 28 '14 at 07:14
  • Wait, do you wish to know how many times each length is used? Anyways, you should try to figure it out yourself. I've already written too much code for you. Isn't this a school assignment? I've definitely written too much code for you. – cubecubed Feb 28 '14 at 07:16
  • @ Cammy_the_blockGrateful! if i understood correct, I have biggestWordsArray[], so i can search it in my str and count it? – user3359479 Feb 28 '14 at 07:23
  • @user3359479 If there is a tie biggestWordsArray[] contains the words. The length is in maxSize. If there isn't a tie the biggest word is in maxWord. The length of the biggest word is still in maxSize. – cubecubed Mar 01 '14 at 00:43
0

Using Map is possibly the most straight-forward and easy way to do. However if you said your teacher don't allow you to use that, may you tell us what is allowed? So that we don't end up wasting time suggesting different methods and end up none of them is acceptable because your teacher doesn't allow.

One most brute force way that I can suggest you to try is (lots of place for optimization, but I think you may want the easiest way):

  1. loop through the list of words, and find out the length of the longest word and number of words with such length
  2. Create a new array with "number of word" you found in 1. Loop through the original word list again, for each word with length == maxWordLength, put that in the new array IF it is not already existed in it (a simple check by a loop.
  3. Now you have a list that contains all DISTINCT words that are "longest", with some possible null at the end. In order to display them in a format like "word : numOfOccurence", you can do something like
  4. loop through result array until you hit null. For each word in the result array, have a loop in the original word list to count its occurence. Then you can print out the message as you want

in psuedo code:

String[] wordList = ....;
int maxLen = 0;
int maxLenOccurence = 0;
foreach word in wordList {
    if word is longer then maxLen {
       maxLen = word's length
       maxLenOccurence = 1;
    } 
    else if word's length is equals to maxLen {
       maxLenOccurence ++
    }
}

// 2,3
String[] maxLenWordList = new String[maxLenOccurence];
foreach word in wordList {
    else if word's length is equals to maxLen {
        for i = 0 to maxLenWordList length {
           if (maxLenWordList[i] == word)
              break
           if (maxLenWordList[i] == null
              maxLenWordList[i] = word
    }
}

//4
foreach maxLenWord in maxLenWordList {
    count = 0
    foreach word in wordList {
       if maxLenWord  == word
          count ++
    }
    display "Max sized word is "+ maxLenWord + " with size " + count
}

Another way doesn't involve other data structure is:

  1. Have the word list
  2. Sort the word list first by length then by the literal value
  3. First element of the result list is the longest one, and string with same value become adjacent. You can do a loop print out all matching and its count (do some thinking by yourself here. Shouldn't be that hard)
Adrian Shum
  • 38,812
  • 10
  • 83
  • 131
-1

Also you can use this;

String[] allLongestStrings(String[] inputArray) {
    List<String> list = new ArrayList<String>();
    int max = 0;

    for (int i = 0; i < inputArray.length; i++) {
        StringBuilder s = new StringBuilder(inputArray[i]);
        int n = s.length();

        if (n > max) {
            max = n;
        }
    }
    
    for (int i = 0; i < inputArray.length; i++) {
        StringBuilder s = new StringBuilder(inputArray[i]);
        int n = s.length();

        if (n == max) {
            list.add(s.toString());
        }
    }
    
    return list.toArray(new String[list.size()]);
}
flaxel
  • 4,173
  • 4
  • 17
  • 30