如何在 C 中确定字符序列的顺序(无数组!)
这就是我到目前为止所做的
char max = 0, here;
while(scanf("%c", &here) == 1 && here != '\n')
if(here > max)
max = here;
printf("max='%c'\n", max);
用户可以输入一个字符序列,然后我会返回具有最高 ASCII 值的字母。在Computer Fun
中,这将是 u。但如果 CompUter Fun
是输入,我想要取回 U,因为它已在序列中首先输入。
我可以有两个变量保存最大的大写字母和最大的简单字母,但是我怎么知道哪个先出现呢?
提前致谢。如果您不想写出执行此操作的代码片段,那么解释逻辑就可以了。
This is what I'm up to so far
char max = 0, here;
while(scanf("%c", &here) == 1 && here != '\n')
if(here > max)
max = here;
printf("max='%c'\n", max);
The user could enter a sequence of characters, and I'd get back the letter with the highest ASCII value. In Computer Fun
, this would be u. But if CompUter Fun
were the input, I'd want to get U back because it has been entered first in the sequence.
I could have two variables saving the highest capital letter and the highest simple letter, but how would I then know which came first?
Thanks in advance. Explaining the logic is just fine, if you don't want to write out the code fragment that does this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需要一个变量 - 只需跟踪到目前为止获胜的角色即可。
当您扫描输入
CompUter Fun
时,您首先会看到C
。因为它是第一个角色,所以它是迄今为止的赢家。然后你会看到o
。o
出现在C
之后,所以它现在是赢家;您的变量现在包含o
。等等。仅当新角色获胜时,您才会替换存储的角色,因此如果出现平局,您将获得第一个角色。(比较时,您需要进行不区分大小写的比较;一种简单的方法是在比较的两侧都
tolower
)。给出最终获胜者 U。
这是一种有效的通用算法,用于查找无序输入的最大值(或最小值,通过反转比较)。它也可以扩展以跟踪第二个(等等)位置,尽管在某些时候排序变得更有效,特别是在这样的数据上,您可以使用基数 O(n) 排序。
You only need one variable—just keep track of the character that wins up to this point.
As you scan over the input
CompUter Fun
, you first seeC
. Since its the first character, its the winner so far. Then you seeo
.o
comes afterC
, so its now the winner; your variable now containso
. And so on. You only replace the stored character if the new one wins, so you'll get the first one in case of ties.(When comparing, you need to do a case-insensitive compare; an easy way to do this is
tolower
on both sides of the compare).gives the ultimate winner, U.
This is an efficient general algorithm for finding the maximum (or minimum, by reversing the compare) of an unordered input. It can also be extended to keep track of 2nd (etc.) place, though at some point sorting becomes more efficient, especially on data like this where you can use radix O(n) sorts.
您可以像您一样只使用一个变量,但不只是检查此处是否> > max,它可以检查新值是否是当前 max 中字母的小写或大写版本。这样,如果出现相同值的新字母,您就不会覆盖当前的最大值。
You could just use one variable like you have, but instead of just checking if here > max, it could check if the new value is a lower case or uppercase version of the letter currently in max. This way you wont overwrite the current max if a new letter of equal value comes along.