【问题标题】:How to get the length of the relevant palindrome of a word in a string?如何获取字符串中单词的相关回文长度?
【发布时间】:2020-01-28 06:42:08
【问题描述】:

我需要获取字符串中单词的回文长度。前任。 我的ot长度=2。 我写了以下代码,但它不起作用。

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {

    char str[20] = "tomyot";
    char rstr[20];
    strcpy(rstr, str);
    strrev(rstr);
    int i,j;
    int count = 0;
    int s=0;

    for(i=0;i<strlen(str); i++){

        for(j=s;j<strlen(str); j++){
            if(str[i] == rstr[j]){
                count+=1;
                s = j+1;
                continue;
            }

        }   

    }
    printf("%d",count);


    return 0;
}

【问题讨论】:

  • 您遇到了什么错误?是输出错误还是编译错误或运行时错误?此外,当字符串为“tomot”时,边缘情况的预期输出应该是什么?
  • strlen() 输出错误
  • 你在代码的什么地方使用了strlen()

标签: c string algorithm


【解决方案1】:

替换

sizeof(str)

strlen(str)

前一个返回str数组的大小,即20,后一个返回str的内容长度,即6

【讨论】:

    【解决方案2】:

    我已经进行了更改并将 cmets 放入 /* .. */ 块中的代码中:

    #include <stdio.h>
    #include <string.h>
    
    int main(void) {
        /*
          - You don't need to compute the reverse of the string, the input string itself will do your work.
          - strrev() is not supported in GCC, so don't use it. See https://stackoverflow.com/a/8534275/4688321
            for alternative implementation
         */
        char str[20] = "tomyot";
        int len_str = strlen(str);
        int i, j, cnt = 0;
        /*
         - You don't need two nested for loops, one loop with two pointers:
           first from the start of string and other from end of the string will do
         - Just compare the ith character (from start) with the jth character (from end)
         - Stop wherever i and j cross each other i.e. when i > j
         */
        for (i = 0, j = len_str - 1; i <= j && i < len_str - 1; i++, j--) {
            if (str[i] == str[j]) {
                cnt++;
            }
            else break;
        }
        printf("%d\n", cnt);
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-30
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 2016-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多