排序字符串和删除字符
#include <iostream>
const int SIZE = 100;
using namespace std;
int main()
{
char *pStr, str[SIZE] = "", newStr[SIZE] = "", ch;
int count = 0, i = 0, j = 0;
cout << "Enter a number of mixed characters: ";
cin.getline(str, SIZE);
pStr = str;
while (*pStr != '\0')
{
if (isalnum(*pStr))
ch = toupper(*pStr);
newStr[i++] = ch;
if (*pStr = ' ')
count++;
pStr++;
}
newStr[i] = '\0';
cout << strlen(str) - strlen(newStr) << " characters were filtered out, "
<< " out of which " << count << " whitespaces were encountered.\n";
int temp;
for (i = 0; i < strlen(newStr) - 1; i++);
{
for (j = i + 1; j < strlen(newStr); j++);
{
if (newStr[j] < newStr[i]) // sorts in alphabetical
{ // and numerical order
temp = newStr[i];
newStr[i] = newStr[j];
newStr[j] = temp;
}
}
}
cout << "New sorted string: " << newStr << endl;
return 0;
}
我在这里有一个代码,应该采取一个输入字符串,并按特定顺序打印出来,并删除其他字符以及空格。数字和字母应按数字和字母顺序排序。所以如果你输入“khff &%/ 321”,输出应该是“123FFHK”。排序字符串和删除字符
但是,当我使用所述输入字符串尝试代码时,我得到的输出是“KHFFFFFF32”。我希望得到一些关于我需要仔细研究以解决问题的代码部分的提示。
我还想指出
if (isalnum(*pStr))
ch = toupper(*pStr);
newStr[i++] = ch;
if条件中不包含每行特殊字符(&,%,/),因此您将在输出中添加额外的Fs。您必须做类似于:
if (isalnum(*pStr))
{ ch = toupper(*pStr);
newStr[i++] = ch;
}
它将检查您的角色是否是alnum,并且只有在满足条件时才会附加。
您可以简单地使用这个代码串排序,你想,然后使用erase
功能剥离出非字母数字字符:
#include <iostream>
#include <algorithm>
#include <string>
int main() {
std::string word = "khff &%/123";
word.erase(std::remove_if(word.begin(), word.end(), [](char ch){ return !::isalnum(ch); }), word.end());
std::sort(word.begin(), word.end());
std::cout << word << '\n';
return 0;
}
为什么在使用窄字符时使用宽字符iswalnum?并进行一些优化:首先删除不需要的字符*然后*排序。 –
@Someprogrammerdude谢谢,修复。 – Annabelle
这里是另一个拿上节目怎么可能被写入使用标准库:
#include <iostream>
#include <sstream>
#include <algorithm>
#include <string>
#include <cstdio>
#define USER_TYPES_INPUT // comment this line out to use own test stream
#ifdef USER_TYPES_INPUT
auto& my_cin = std::cin;
#else
std::stringstream my_cin{R"(khff&%/32 1)"};
#endif
int main()
{
std::string line;
std::cout << "Enter a number of mixed characters: \n";
std::getline(my_cin, line);
auto original_size = line.size();
auto space_count = std::count_if(line.begin(), line.end(), [](auto c){return ::isblank(c); });
line.erase(std::remove_if(line.begin(), line.end(), [](char c){ return !::isalnum(c); }), line.end());
std::transform(line.begin(), line.end(), line.begin(), [](auto& c){return ::toupper(c); });
std::sort(line.begin(), line.end());
std::cout << original_size - line.size() << " characters were filtered out, out of which "
<< space_count << " whitespace" << (space_count == 1 ? " was" : "s were") << " encountered.\n";
std::cout << "New sorted string: " << line << '\n';
return 0;
}
我建议你阅读[如何调试小程序(https://ericlippert.com/2014/03/05/how-to-debug-small-programs /)作者:Eric Lippert,并学习如何使用调试器。 –
我还假设这是一个练习指针,数组和C风格的字符串?否则,如果你使用标准的类和算法,它将只是几行。 –
'str [SIZE] =“”'不符合你的想法。你的排序算法严重错误。看看'std :: sort','std :: remove_if'和'std :: transform' – IlBeldus