Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using strlen in loop reversing a string in C

Tags:

c

string

I'm trying to write a code where I input a String and I get it reversed. I.e.: "nokia" to "aikon".

I already have it in a way, but now I want to use the function strlen() to get the original String's length and create the new one based on that length.

Here is the code:

void main(void)
{
    char palavra[10];
    char palavra2[10];
    int i;
    int k;

    printf("Introduza uma string: \n");
    scanf("%[^\n]", palavra);

    for( i = 0, k = strlen(palavra) - 1 ; i <= k; i++, k--)
    {
        palavra2[k] = palavra[i];
    }
    printf("\nString invertida: %s", palavra2);
}

However all I get from my printf() is a "?". What am I doing wrong?

like image 892
Nelson Silva Avatar asked Feb 05 '23 14:02

Nelson Silva


2 Answers

your loop indexes are running the opposite ways so they meet in the middle and the loop stops when i <= k: half of the string is not inverted. Just test i against strlen(palavra)

Plus you have to null-terminate your string:

int len=strlen(palavra);
for( i = 0, k = len - 1 ; i < len; i++, k--)
{
    palavra2[k] = palavra[i];
}
palavra2[len]='\0';

(and you'd better store the value of strlen(palavra) so you have to compute it only once)

like image 162
Jean-François Fabre Avatar answered Feb 08 '23 04:02

Jean-François Fabre


Try this simple reverse function:

/* reverse:  reverse string s in place */
void reverse(char s[])
{
    int c, i, j;

    for (i = 0, j = strlen(s)-1; i < j; i++, j--) {
        c = s[i];
        s[i] = s[j];
        s[j] = c;
    }
}

To integrate it into your code:

void main(void)
{
    char palavra[10];
    int c, i, j;

    /* read the string */
    printf("Introduza uma string: \n");
    scanf("%[^\n]", palavra);

    /* null-terminate the string */
    palavra[strlen(palavra)] = '\0';

    /* reverse the string */
    for (i = 0, j = strlen(palavra)-1; i < j; i++, j--) {
        c = palavra[i];
        palavra[i] = palavra[j];
        palavra[j] = c;
    }

    printf("\nString invertida: %s", palavra);
}
like image 34
MD XF Avatar answered Feb 08 '23 04:02

MD XF