简体   繁体   English

使用指针反转字符串

[英]Using pointers to reverse a String

Trying to reverse a String in C using pointers and I can't seem to figure out what's wrong with my code.尝试使用指针反转 C 中的字符串,我似乎无法弄清楚我的代码有什么问题。 Does anyone know why this isn't working?有谁知道为什么这不起作用?

int main(void) 
{
    char sentence[100];
    printf("Enter any string: ");

    scanf("%[^\n]s", sentence);

    char *sPtr;
    sPtr = sentence;
    int length = 0;

    printf("Original string = %s\n", sentence);

    while (*sPtr != '\0') {
        ++length;
        ++sPtr;
    }

    printf("Reverse string = ");

    for (int i = length; i >= 0; --i) {
        printf("%c", *(sPtr + 1));
    }

    puts("");
    return 0;
}

The error is here:错误在这里:

while (*sPtr != '\0') {
    ++length;
    ++sPtr;
}

At this point the sPtr point at the end of the string so in the second loop it never decrement.此时 sPtr 指向字符串末尾,因此在第二个循环中它永远不会递减。

for (int i = length; i >= 0; --i) {
    printf("%c", *(sPtr+1));
}

A possible solution can be this:一个可能的解决方案是这样的:

for (int i = length; i >= 0; --i) {
    printf("%c", *(sPtr));
    --sPtr;
}

You are always print a character past the end of the string.您总是在字符串末尾打印一个字符。

for (int i = length; i >= 0; --i) {
    printf("%c", *(sPtr+1));
}

should be应该

for (int i = length-1; i >= 0; --i) {
    printf("%c", *(sPtr-(length-i));
}

or或者

   for (int i = length; i >= 0; --i) {
        sPtr--; //decrement first as sPtr will be pointing to \0 char
        printf("%c", *sPtr);
    }

This is the solution I came up with.这是我想出的解决方案。 Thanks for the help anyone provided!感谢任何人提供的帮助!

while (*sPtr != '\0') {
    ++length;
    ++sPtr;
}

printf("Reverse string = ");

sPtr = sentence;

for (int i = length; i >= 0; --i) {
    printf("%c", *(sPtr+length));
    --sPtr;
}
  1. Write separate functions for such a tasks.为此类任务编写单独的函数。
  2. When you test the function try to reduce number of unknown factors.当您测试函数时,尝试减少未知因素的数量。 In your case do not scanf just use known strings.在你的情况不scanf只是用已知的字符串。 scanf may fail and you will not know if it your function, or the user input. scanf 可能会失败,您将不知道它是您的功能还是用户输入。

Simple function, no library functions used.函数简单,不使用库函数。

char *reverse(char *str)
{
    char *head = str, *tail = str;

    if(str && *str)
    {
        while(*tail) tail++;
        tail--;
        while(tail > head)   
        {
            int ch = *tail;
            *tail-- = *head;
            *head++ = ch;
        }
    }
    return str;
}

https://godbolt.org/z/EgNLpF https://godbolt.org/z/EgNLpF

After this loop在这个循环之后

while (*sPtr != '\0') {
    ++length;
    ++sPtr;
}

the pointer sPtr points to the terminating zero.指针 sPtr 指向终止零。 So in the next loop you are starting to output the string from the indeterminate character after the terminating zero.因此,在下一个循环中,您将开始从终止零之后的不确定字符中输出字符串。

for (int i = length; i >= 0; --i) {
    printf("%c", *(sPtr+1));
}

The expression *(sPtr+1) is not being changed in the loop.表达式*(sPtr+1)在循环中没有改变。

Take into account that you are not reversing a string.考虑到您没有反转字符串。 You are trying to output a string in the reverse order.您正在尝试以相反的顺序输出字符串。 It is not the same.它不一样。 Also you are using an intermediate variable of the type int.此外,您正在使用 int 类型的中间变量。

To reverse a string using only pointers the code can look the following way.要仅使用指针反转字符串,代码可以如下所示。

char *last = sentence;

while ( *last ) ++last;

if ( sentence != last )
{
    for ( char *first = sentence; first < --last; ++first )
    {
        char c = *first;
        *first = *last;
        *last = c;
    }
}

printf( "Reversed string = %s\n", sentence );

Here is a demonstrative program.这是一个演示程序。

#include <stdio.h>

int main(void) 
{
    char sentence[100] = { '\0' };

    printf( "Enter any string: " );
    scanf("%99[^\n]s", sentence );

    char *last = sentence;

    while ( *last ) ++ last;

    if ( sentence != last )
    {
        for ( char *first = sentence; first < --last; ++first )
        {
            char c = *first;
            *first = *last;
            *last = c;
        }
    }

    printf( "Reversed string = %s\n", sentence );

    return 0;
}

Its output might look like它的输出可能看起来像

Enter any string: Hello Jordan
Reversed string = nadroJ olleH

You could write a separate function that reverse a string.您可以编写一个单独的函数来反转字符串。 Just move the code that reverses a string from main into a separate function like只需将将字符串从 main 反转的代码移动到一个单独的函数中,例如

#include <stdio.h>

char * reverse( char *s )
{
    char *last = s;

    while ( *last ) ++last;

    if ( s != last )
    {
        for ( char *first = s; first < --last; ++first )
        {
            char c = *first;
            *first = *last;
            *last = c;
        }
    }

    return s;
}

int main(void) 
{
    char sentence[100] = { '\0' };

    printf( "Enter any string: " );
    scanf("%99[^\n]s", sentence );

    printf( "Revresed string = %s\n", reverse( sentence ) );

    return 0;
}

If you want just to output a string in the reverse order using pointers then the program can be very simple.如果您只想使用指针以相反的顺序输出字符串,那么程序可以非常简单。

Here you are.这个给你。

#include <stdio.h>

int main(void) 
{
    char sentence[100] = { '\0' };

    printf( "Enter any string: " );
    scanf("%99[^\n]s", sentence );

    const char *sPtr = sentence;

    while ( *sPtr ) ++ sPtr;

    printf( "Revresed string = ");

    while ( sPtr != sentence ) putchar( *--sPtr );
    putchar( '\n' );

    return 0;
}

Even more simply implementation you could make by means of a recursive function.您可以通过递归函数进行更简单的实现。 For example例如

#include <stdio.h>

void reversed_output( const char *s )
{
    if ( *s )
    {
        reversed_output( s + 1 );
        putchar( *s );
    }
}

int main(void) 
{
    char sentence[100] = { '\0' };

    printf( "Enter any string: " );
    scanf("%99[^\n]s", sentence );

    printf( "Revresed string = ");

    reversed_output( sentence );
    putchar( '\n' );

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM