Как узнать длину соответствующего палиндрома слова в строке? - PullRequest
0 голосов
/ 28 сентября 2019

Мне нужно получить длину палиндрома слова в строке.Ex. до my 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;
}

Ответы [ 2 ]

2 голосов
/ 28 сентября 2019

Заменить

sizeof(str)

на

strlen(str)

Первый возвращает размер массива str, равный 20, а второй возвращает длину содержимогоstr, что составляет 6.

0 голосов
/ 29 сентября 2019

Я внес изменения и разместил комментарии в коде в /* .. */ блоках:

#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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...