简体   繁体   English

用 char aaryas 反转字符串

[英]Reversing string with char aaryas

I'm learning C now, and i have one question in my program.我现在正在学习 C,我的程序中有一个问题。
I need to reverse string like我需要反转字符串
I like dogs -> I ekil sgod I wrote this code I like dogs -> I ekil sgod我写了这段代码

char end[MAX_LEN];
char beg[MAX_LEN];
char* piece = strtok(str, " ");
strcpy(end, piece);
strcpy(beg, piece);
char* pbeg = beg;
char* prev = piece;
int n = strlen(piece)-1;
i = 0;
int n = 0;

while (piece != NULL) {
    //printf("\n%s", piece);
    while (piece[i] != '\0') {
        *(prev + n -i ) = *(pbeg + i);
            i++;
    }

    printf("\n%s", piece);
    piece = strtok(NULL, " ");
    strcpy(beg, piece); // also in this moment in debugging i saw this error ***Exception thrown at 0x7CBAF7B3 (ucrtbased.dll) in лаб131.exe: 0xC0000005: Access violation reading location 0x00000000.***
}

But it returns only the first lexeme reversed.但它只返回第一个反转的词素。

You are getting an exception because you are not checking whether the pointer piece is equal to NULL when you are using it in the call of strcpy你得到一个例外,因为当你在 strcpy 的调用中使用它时,你没有检查指针片段是否等于 NULL

piece = strtok(NULL, " ");
strcpy(beg, piece);

Also within the while loop you forgot to reset the variables i and n and the pointer prev .同样在 while 循环中,您忘记重置变量in以及指针prev

To use the function strtok is a bad idea because the source string can contain adjacent space characters that should be preserved in the result string.使用 function strtok 是一个坏主意,因为源字符串可能包含应保留在结果字符串中的相邻空格字符。 Also you have too many arrays and pointers that only confuse readers of the code.此外,您还有太多的 arrays 和只会混淆代码读者的指针。

Here is a demonstration program that shows how the task can be easy done.这是一个演示程序,展示了如何轻松完成任务。

#include <stdio.h>
#include <string.h>

void reverse_n( char s[], size_t n )
{
    for ( size_t i = 0; i < n / 2; i++ )
    {
        char c = s[i];
        s[i] = s[n-i-1];
        s[n-i-1] = c;
    }
}

int main(void) 
{
    char input[] = "I like dogs";
    
    const char *separator = " \t";
    
    for ( char *p = input; *p; )
    {
        p += strspn( p, separator );
        char *q = p;
        
        p += strcspn( p, separator );
        
        reverse_n( q, p - q );
    }
    
    puts( input );
    
    return 0;
}

The program output is程序 output 是

I ekil sgod

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

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