我正在尝试编写一个具有两个功能的代码:一个确定字符串是否为 等值线图 或者不和另一个将结果(真或假)打印到控制台(为了解决任务)。
但是,有些事情无法正常工作。我想知道我需要改进代码的地方(可能全部......)。我将不胜感激任何建议:)
#include <iostream>
#include<string>
#include<bits/stdc++.h>
#include<iomanip>
bool find_Isogram (std::string str)
{
std::sort(str.begin(), str.end()); //sorted the string for the for loop (e.g. eHllo)
int length = str.length();
for (int i = 0; i < length; i++)
{
if (str.at(i) == str.at(i+1))
{
return false;
break;
}
else
{
return true;
}
}
}
void print_result()
{
std::string str;
if (!find_Isogram (str))
{
std::cout << "false" << std::endl;
}
else
{
std::cout << "true" << std::endl;
}
}
int main()
{
find_Isogram ("gdtub");
print_result();
return 0;
};
````````````````````````````````````````````````````
最佳答案
这里有一些问题:
1)你总是检查一个空字符串:print_result
只会检查一个空字符串,但无论如何它都是多余的。
void print_result()
{
std::string str; // empty string
if (!find_Isogram (str)) // finding isogram on empty string
{
std::cout << "false" << std::endl;
}
...
}
可以用 std::boolalpha
简化允许您打印 bool
如 "true"
或 "false"
(而不是 1 或 0)。 main
会成为int main()
{
std::cout << std::boolalpha << find_Isogram ("gdtub"); // prints true or false
};
2) 等值线检查总是在第一个字符后结束查看
find_Isogram
中的条件.它有一个 return
-声明在if
和 else
,所以你总是在检查第一个字符后返回。以这种方式检测重复字符的想法是正确的(除了其他人已经提到的逐一错误)。但是你要
return true;
只有在检查所有字符后,例如循环外:bool find_Isogram (std::string str)
{
std::sort(str.begin(), str.end()); //sorted the string for the for loop (e.g. eHllo)
int length = str.length();
for (int i = 0; i < length - 1; i++)
{
if (str.at(i) == str.at(i+1))
{
return false; // whoops duplicate char, stop here
}
}
return true; // no duplicates found, it's an isogram
}
对于一些进一步的 C++-magic,您可以使用标准库函数进一步简化它:D
bool find_Isogram (std::string str)
{
std::sort(str.begin(), str.end());
return std::unique(str.begin(), str.end()) == str.end();
}
关于c++ - 试图在字符串 C++ 中找到等值线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62651837/