【问题标题】:Removing white space and special characters from a c string [duplicate]从c字符串中删除空格和特殊字符[重复]
【发布时间】:2015-01-13 20:18:38
【问题描述】:

所以我正在制作一个忽略任何空格或特殊字符的回文检查器。以下是我的功能的一部分。它的作用是将一个 c 字符串作为参数,然后我创建另一个 c 字符串以从原始字符串中删除空格和特殊字符。当我输出第二个 c 字符串时,它仍然会有空格或特殊字符。有人可以解释为什么这样做吗?谢谢

bool isPalindrome(char *line)
{
   //variables
   bool palindrome = true;
   int length = strlen(line);
   int count = 0;


   //copy line to line2 with no spaces and no punctuation
   char *line2 = new char[length + 1];
   int count2 = 0;

   for(int i = 0; i < length; i++)
   {
      if(line[i] != ' ' && ispunct(line[i]) == false)
      {
         line2[count2] = line[i];
         count2 ++;
      }
   }
   for(int i = 0; i < count2; i++)
       cout << line[i];
   line2[length] = '\0';

【问题讨论】:

标签: c++ c-strings


【解决方案1】:

您正在以原始长度终止第二个字符串:

line2[length] = '\0';

应该是

line2[count2] = '\0';

就您的原始作业而言,没有必要创建字符串的副本来检查它是否是回文:您所需要的只是一个函数,它可以在字符串中查找下一个非空、非标点字符具体方向:

int nextValidChar(const char *str, int &pos, const int step) {
    pos += step;
    while (pos >= 0 && str[pos] != '\0') {
        char c = str[i];
        if (c != ' ' && !ispunct(c)) {
            return c;
        }
        pos += step;
    }
    return -1;
}

有了这个函数,在零和length-1处设置两个索引,反复调用nextValidChar寻找两端的有效字符。

【讨论】:

    【解决方案2】:

    它仍然输出空格和特殊字符的原因是因为这个

    for(int i = 0; i < count2; i++)
       cout << line[i];
    

    应该是

    for(int i = 0; i < count2; i++)
       cout << line2[i];
    

    【讨论】:

    • 抱歉回复晚了,谢谢第二双眼睛:)
    猜你喜欢
    • 2021-10-16
    • 2014-08-17
    • 2014-05-20
    • 1970-01-01
    • 2021-04-23
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    相关资源
    最近更新 更多