c语言字符串-常用操作(3) 字符串 翻转

字符串翻转(一般有两个类型):

Hello World   --->  dlroW olleH

Hello World   --->  World Hello


第一种类型见另一篇blog:字符串翻转


第二种类型:

//
//  main.c
//
//  Created by yjsong on 16/3/24.
//  Copyright © 2016年 yjsong. All rights reserved.
//

#include <stdio.h>
#include <assert.h>


//逆转整个限定范围内的字符串
char* reserve(char* str, int length)
{
    char * p1 = str;
    char * p2 = str - 1 + length;
    while(p1<p2)
    {
        char c = *p1;
        *p1++ = *p2;
        *p2-- = c;
    }
    return str;
}


char* reverseS(char *s , int length)
{
    reserve(s, length);//整个字符串翻转
    printf("%s\n",s);
    char *p = s;
    char *t = s;
    int tempLength = 0;
    for (int i = 0; i < length; i++) {
        if (i == length - 1) {
            reserve(t, tempLength + 1);
        }else if (*p == ' ') {
            reserve(t, tempLength);
            tempLength = 0;
            t = p + 1;
        }else
        {
            tempLength++;
        }
        p++;
    }
    
    return s;
}

int main(int argc, const char * argv[]) {
    char c[] = "Hello World";
    char *p = c;
    
    printf("%s\n",p);
    printf("%s\n",reverseS(p, 11));
    return 0;
}

运行结果:

Hello World

dlroW olleH

World Hello

Program ended with exit code: 0



主要思路:

1.把整个字符串翻转dlroW olleH

2.逐个单词翻转,把每一个字符串中的每个单词翻转,World Hello


个人blog其他关于字符串操作的文章:

c语言字符串-常用操作(1)

c语言字符串-常用操作(2)

相关文章
相关标签/搜索