c - 不使用 sting 库交换字符串的单词并使用指针

标签 c

我锻炼的目标是产出

原始字符串是:

沉默是一只正在寻找的鸟:转向;边缘,生命的边缘。 e. e.卡明斯

交换后的目标字符串: 卡明斯 e. e.生活。边缘、车削;鸟:看着.就是沉默

我得到的是:

69原始字符串是: 沉默是一只正在寻找的鸟:转身;边缘,生命的边缘。 e. e.卡明斯

交换后的目标字符串:

我的代码: '''

#include<stdio.h>
#include<stdlib.h>
#define MAX_STR_LEN 1024
// DO NOT USE the string library <string.h> for this exercise
void wordSwapper(char *source, char *destination)
{  
    int count = 0;
    while (*(source + count) != '\0')
    {
        count++;
    }
    printf("%d", count);
    for(int i = 0; i < count; i++) 
    {
        *(destination + i) = *(source + (count - i));
    }
}

int main()
{    
    char source[MAX_STR_LEN]="silence .is a looking bird:the turning; edge, of life. e. e. cummings";    
    char destination[MAX_STR_LEN]="I am a destination string and I contain lots of junk 1234517265716572@qsajdkuhasdgsahiehwjauhiuiuhdsj!"; 
    wordSwapper(&source[0], &destination[0]);   
    printf("The original string is: \n%s\n",source);    
    printf("Destination string after swapping: \n%s\n",destination);    
}

'''

最佳答案

我的变体:

void wordSwapper(char *source, char *destination)
{  
    char *start, *end;

    start = source;
    while (*(start++) != '\0')
        destination++;

    // write trailing zero
    *destination = '\0';

    while (*source != '\0')
    {
        // copy spaces
        while (*source == ' ')
            *(--destination) = *(source++);

        // find word bounds
        start = end = source;
        while (*end != '\0' && *end != ' ')
            end++;

        source = end;

        // copy word
        while (end > start)
            *(--destination) = *(--end);
    }
}

关于c - 不使用 sting 库交换字符串的单词并使用指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59920984/

相关文章:

C - 为什么我不能从本地主机外部访问我的服务器?

c - 如何使用除以1000作为CPU优化?

c - NUC串口打开失败

标准的字符串文字和字符串文字?

c - 是否可以在ncurses库中绘制如下图表并实时更新?

c - 我在下面提到的程序中遇到问题,为指针分配一个值。字符串连接程序(* s1 = * s2)

c - 将堆栈变量传递给 pthread_cleanup_push

C GPIO for 循环

c - 将 NULL 分配给指针是否是错误的编程?

c - getchar函数清除while-condition之外的输入缓冲区?