simi kaur
simi kaur

Reputation: 1277

Dealing with next line character in C

I have written a program to check if two given strings are palindromes.

It works fine but the test cases sometimes include a new line char appended at the end of the string and need that to be ignored. For example:

Two passed strings are:

india\n
aidni

and response should be that Yes, these are palindromes.

My code looks like this:

#include <stdio.h>

int main(void)
{
    char arr1[100];
    char arr2[100];
    int i = 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;

        for (i = 0; i < 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" for india and aidni but no for india\n and aidni.

Upvotes: 0

Views: 88

Answers (2)

Bill Lynch
Bill Lynch

Reputation: 81926

So there's a significant amount of confusion.

It wasn't originally clear if the \n in your input was one character, or two. It sounds like it's two.

What should we do?

So, what we need to do, is take two strings as input, apply a filter to those strings to remove characters that we are not interested in. And then do our palindrome test.

How might we do this?

I've added a call to a new function called cleanup(). This function will remove any sequence of a backslash followed by an n from the given string. I've also cleaned up the end code by just reversing one of the strings, and then seeing if they are 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;

    for (i=0; i<len/2; ++i) {
        char temp = s[i];
        s[i] = s[len - i - 1];
        s[len - i - 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!

Upvotes: 3

Bob
Bob

Reputation: 1851

Not the most efficient solution but you could iterate through the strings, check for the newline character, and remove it before running your comparison code.

Upvotes: -1

Related Questions