Sorting words C++

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
?
Last edited on
Yes!
So how I need to do that?
I think that
1
2
3
4
5
6
7
8
9
void Do(Book & B1, Book & B2){
string word;
for(int i=0; i<B1.N(); i++){
word = B1.GetWord(i);
for(int j  = 1; j<B2.N()-1; j++){
if(word.lenght() < B2.GetWord(j);
}
}
}
Any ideas?
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'
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
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
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
What do you mean?
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
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
Bad, I can't even finf the mistake. I'm really depressed... I have no idea what's wrong with my code...
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
Line 7: length() gives me a lenght of a word
Topic archived. No new replies allowed.