【问题标题】:bool function will not properly compare arraysbool 函数将无法正确比较数组
【发布时间】:2012-03-19 04:22:32
【问题描述】:

正在开发一个小程序,该程序将从用户那里获取一个字符串并查看它是否是回文。 (一个向后拼写相同的短语,例如“从不奇数或偶数”)我已经构建了从字符串中删除空格和任何非字母字符的函数,然后也复制了字符串。 (所有这三个函数都经过了全面测试,没有问题。)现在我正在研究一个需要比较两个字符串的函数,以查看字符串的前后拼写是否相同。

函数应该通过向前循环主字符串和向后循环并比较每个元素来确定它是否是回文。然而我总是得到一个错误的答案,我做错了什么?

_Bool isPalindrome(char str[], char copy[])
{
  int i = 0;
  int count = 0, j = 0;

  // loop through the main string to find the number of elements
  while(str[j] != '\0')
  {
     count++;
     j++;
  }

  //loop through the main string until the null character.
  while(str[i] != '\0')
  {
    // to loop through the copy backwards, 
    // use the size of the first and subtract i
    size = count - i;
    if(str[i] != copy[size])
      return FALSE;
    i++;
  }

  return TRUE;
}

【问题讨论】:

  • 试试调试器?你的第一个循环也相当于strlen
  • 用笔和纸以及两个长度为一个字符的输入字符串运行您的代码。看看会发生什么。

标签: c arrays string function boolean


【解决方案1】:

应该是:

   size = count - i - 1;

【讨论】:

    猜你喜欢
    • 2013-07-05
    • 1970-01-01
    • 2013-12-18
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    相关资源
    最近更新 更多