Click here to Skip to main content
15,894,405 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I'm trying to write a program that can compare strings inputted by the user and then output them in the order of their size from smallest to largest (example: Biggest, bigger, big, is outputted as big, bigger, Biggest regardless of the order of the word.). I was able to compare numbers inputted by the user using <= and && operators, but these operators don't seem to help me for comparing strings. I'm working from Exercise 7 on Pg. 85 of Programming: Principles and Practice using C++ by Bjarne Stroustrup. I haven't found anything on google easily describing what I'm trying to do. I have not been introduced to arrays, vectors, or pointers at this point in the text. Although I have been introduced to variables, if-statements, and basic operators.

Thank you
Posted
Updated 26-Jul-13 4:15am
v2
Comments
max_nowak 26-Jul-13 10:29am    
Do you mean by 'their size' their length? If so, you can use strlen() (or std::string::length if you use stl) to determine the length of the string, which in turn you can leverage to compare them.

If you have not been introduced to arrays and vectors, then I suggest you look into that before continuing. ( and maybe std::string )


I Assume you know how to get the length of a a string ? (std::string::size() or std::string::length() )

Once you have the length or the strings, then you can sort the string according to their size.

for example, you can put the strings in a std::vector and use std::sort to sort the vector.

C++
std::vector<std::string xmlns:std="#unknown"> vectorOfString; // filled with strings.
...

// you need to defined the SortCondition predicate to compare the string lengths... 
// left as an exercises)
std::sort(vectorOfString.begin(), vectorOfString.end(), SortCondition );
</std::string>
 
Share this answer
 
You have to compare the length of the strings not the string itself.

if you use std::string to store one of your string, you can use the length method:
C++
std::string mystring;
int mystring_length = mystring.length();


if you use an array of char to store the strings, you can use a function to get the length:
C++
int mystringlength=strlen(mystring);


or basically found the number of char before the end character ('\0')

I hope this will help you to find the solution of your exercise.
 
Share this answer
 
Comments
UniversalMutt 26-Jul-13 10:45am    
Thank you very much, I was able to compare the length of the strings after placing them into integers and then output the strings inputted by the user. I didn't know about the .length() tool.

Thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900