比较C ++中的字符串,使它们从最小的单词输出到最大的单词。 [英] Comparing Strings in C++ so they output from the smallest word to the largest.

查看:99
本文介绍了比较C ++中的字符串,使它们从最小的单词输出到最大的单词。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在尝试编写一个程序,可以比较用户输入的字符串,然后按照从最小到最小的顺序输出它们最大的(例如:最大,更大,更大,输出为大,大,最大,无论单词的顺序。)。我能够使用< =和&&运算符比较用户输入的数字,但这些运算符似乎不能帮助我比较字符串。我正在练习7上的Pg。 85编程:Bjarne Stroustrup使用C ++的原理和实践。我没有在谷歌上找到任何容易描述我正在尝试做什么的东西。我没有在文本的这一点上介绍过数组,向量或指针。虽然我已经介绍过变量,if语句和基本运算符。



谢谢

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

推荐答案

如果你还没有介绍过数组和向量,那么我建议你在继续之前先研究一下。(也许是std :: string)





我假设您知道如何获得字符串的长度? (std :: string :: size()或std :: string :: length())



一旦你有了长度或字符串,那么你可以排序字符串根据它们的大小。



例如,你可以将字符串放在std :: vector中并使用std :: sort来对矢量进行排序。 />


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.

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>


你必须比较字符串的长度而不是字符串本身。



如果你使用std :: string存储你的一个字符串,你可以使用length方法:

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:
std::string mystring;
int mystring_length = mystring.length();





如果使用char数组来存储字符串,则可以使用函数来获取长度:



if you use an array of char to store the strings, you can use a function to get the length:

int mystringlength=strlen(mystring);





或基本上找到结束字符前的字符数('\ 0'



我希望这能帮助您找到锻炼的解决方案。



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.


这篇关于比较C ++中的字符串,使它们从最小的单词输出到最大的单词。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆