Nov 20, 2013 at 4:49pm UTC
Hello i have this quote
Friendship is born at that moment when one person says to another: "What! You too? I thought that no one but myself . . .
And I want to sort words from largest to sortest. Any idea how to do that? Thanks :)
Last edited on Nov 20, 2013 at 4:50pm UTC
Nov 20, 2013 at 5:26pm UTC
?
Last edited on Nov 20, 2013 at 7:32pm UTC
Nov 20, 2013 at 7:47pm UTC
Think of it logically, each word is separated by a space. so have an increment variable that counts how long a word is.
IF a space: (IF ' ') is detected THEN a new word has begun. store how long that word is, compare it to previous word.
IF it has more characters THEN your longest word is now the word you are looking at.
do this until you reach a '\0'
Nov 20, 2013 at 7:53pm UTC
Ok i have made that each word is seperated from other so my file looks something like that
Friendship
is
born
at
that
moment
...
...
...
...
...
so on.
Last edited on Nov 20, 2013 at 7:53pm UTC
Nov 20, 2013 at 7:59pm UTC
You don't have to modify your file.
Make this change in your program.
1) Find how long your string is
2) use this length to determine how many indexes you have in your c-string
3) Take this knowledge, make a for-loop
4)
1 2 3 4 5 6 7
for (int i = 0; char [i] != '\0' ; i++)
{
if (char [i] == ' ' )
//You have a new word, how long was it? If longer than previous word, switch the two
else
//Still the same word. increment your character counter
}
5) If your previous word is shorter than your current word, your current word is longer, switch the two.
Last edited on Nov 20, 2013 at 8:03pm UTC
Nov 20, 2013 at 8:12pm UTC
Thanks for reply :). Still I wonder if it's possible to short everything on my way? Because for me it is much easier and better to short every word in one line ant then make changes. Thanks ;)
Last edited on Nov 20, 2013 at 8:14pm UTC
Nov 20, 2013 at 8:26pm UTC
How I need to sort this kind of text
Friendship
is
born
at
that
moment
...
...
...
...
...
so on.
I need to sort from longest to shortest word. Is it possible to do that for example with bubble method? Thanks for reply
Last edited on Nov 20, 2013 at 8:27pm UTC
Nov 20, 2013 at 9:44pm UTC
And what's wrong with my sorting?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
void Sort(Book & Kn1, Book & Kn2){
string Rik;
int m;
for (int i=0; i<Kn1.GetN(); i++){
m = i;
for (int j = i+1; j<Kn1.GetN(); j++){
if (Kn1.Get(i).lenght() < Kn1.Get(j).lenght()){
m = j;
}
}
Rik = Kn1.Get(i);
Kn1.Get(i) = Kn1.Get(m);
Kn1.Get(m) = Rik;
}
}
Last edited on Nov 20, 2013 at 10:12pm UTC
Nov 20, 2013 at 10:22pm UTC
Bad, I can't even finf the mistake. I'm really depressed... I have no idea what's wrong with my code...
Nov 20, 2013 at 10:39pm UTC
Line 7: Is that member function really called lenght?
Lines 11-13: Shouldn't those be in your if statement, and using just i and j instead of an additional temporary variable?
-Albatross
Nov 21, 2013 at 11:03am UTC
Line 7: length() gives me a lenght of a word