使用 strcmp 在数组中查找匹配项
我试图使用 strcmp 比较数组的单词。我试图让数组中出现多次的每个单词只打印一次,这样我就可以确定唯一单词的数量。我知道它做错了什么搜索它打印出它找到的每个副本的数组,例如,如果单词“the”在数组中出现 4 次,它将打印出“the”3 次,并且当 string1
转到下一个位置时其中“the”在哪里,它将打印出去2次等等。
im trying to compare words of an array using strcmp.Im trying to get each word that appears more than once in the array to print out only once, so i can determine the number of unique words.I know what its doing wrong as when it searches the array it prints out each copy it finds, for example if the word "the" is in the array 4 times, it will print out 'the' 3 times and when string1
goes to the next location where 'the' is, it will print out 2 times and so on.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将您的 char 数组转换为
std::string
,而不是打印它们,而是将它们放入std::set
中。然后打印集合中的每个元素。Convert your char arrays to
std::string
and instead of printing them, put them into anstd::set
. Then print each element in the set.很好,您添加了声明,
现在从表面上看,words[][] 似乎是多余的,并使事情变得不必要的复杂化。如果您只对获取唯一单词感兴趣,则只需通过使用遇到的单词构建字典来处理从 strtrok 返回的内容,
字典可以像包含唯一单词的最大大小的数组一样简单,并且索引从 0 开始当数组为空时,每当 strtok 返回一个单词时,都会遍历数组并使用 strcmp 查找该单词,如果不存在,则将其添加到数组末尾,然后递增索引。
鲍勃是你叔叔:)
good that you added declarations,
now from what it looks it seems as if words[][] is redundant and makes things unnecessary complicated. if you are only interested in getting unique words, instead just process what comes back from strtrok by building up a dictionary with the encountered words
a dictionary could be something as simple as a max sized array containing unique words, and an index that starts at 0 when array is empty, whenever strtok returns a word, go through the array and look for the word using your strcmp, if it doesn't exist add it at the end of the array then increment then index.
and bob is your uncle :)