Dealing with next line character in C -


i have written program check if 2 given strings palindromes.

it works fine test cases sometimes include new line char appended @ end of string , need ignored. example:

two passed strings are:

india\n aidni 

and response should yes, these palindromes.

my code looks this:

#include <stdio.h>  int main(void) {     char arr1[100];     char arr2[100];     int = 0, j = 0;     int len1 = 0, len2 = 0;      scanf("%s", arr1);     scanf("%s", arr2);      while (arr1[i] != '\0')         i++;     len1 = i;      while (arr2[j] != '\0')         j++;     len2 = j;      if (i != j) {         printf("%s", "no");         return 0;     } else {         int count = 0;          (i = 0; < len1; i++)             if (arr1[i] == arr2[len1-i-1])                 count++;          if (count == len1)             printf("%s", "yes");         else             printf("%s", "no");     }      return 0; } 

the above code gives output "yes" india , aidni no india\n , aidni.

so there's significant amount of confusion.

it wasn't clear if \n in input 1 character, or two. sounds it's two.

what should do?

so, need do, take 2 strings input, apply filter strings remove characters not interested in. , our palindrome test.

how might this?

i've added call new function called cleanup(). function remove sequence of backslash followed n given string. i've cleaned end code reversing 1 of strings, , seeing if identical.

#include <stdio.h> #include <string.h>  void cleanup(char *s) {     char *source = s;     char *destination = s;      while (*source != '\0')         if (source[0] == '\\' && source[1] == 'n')             source += 2;         else             *destination++ = *source++;     *destination = '\0'; }  void reverse(char *s) {     int len = strlen(s);     int i;      (i=0; i<len/2; ++i) {         char temp = s[i];         s[i] = s[len - - 1];         s[len - - 1] = temp;     } }  int main() {     char arr1[100];     char arr2[100];      scanf("%s", arr1);     scanf("%s", arr2);      cleanup(arr1);     cleanup(arr2);     reverse(arr2);      if (strcmp(arr1, arr2) == 0)         printf("yes\n");     else         printf("no!\n"); } 

when run:

[3:28pm][wlynch@watermelon /tmp] ./orange  india\n aidni yes [3:28pm][wlynch@watermelon /tmp] ./orange ind\nia aidn\ni yes [3:29pm][wlynch@watermelon /tmp] ./orange blue green no! 

Popular posts from this blog