首页 > 代码库 > 反转字符串(c语言)

反转字符串(c语言)

简单的反转字符串实现

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

void exchange(char *string, int c1, int c2);
void revertString(char *string, int iStart, int iEnd);

int main(int argc, const char * argv[])
{

    // insert code here...
    printf("Begin>>>!\n");
    
    char originalString[100] = "abcdef";
    printf("%s\n", originalString);
    size_t len = strlen(originalString);
    revertString(originalString, 0, (int)(len-1));
    printf("%s\n", originalString);
    
    
    return 0;
}

void revertString(char *string, int iStart, int iEnd)
{
    while (iStart < iEnd) {
        exchange(string, iStart, iEnd);
        iStart++;
        iEnd--;
    }
}

void exchange(char *string, int c1, int c2)
{
    char tmp = string[c1];
    string[c1] = string[c2];
    string[c2] = tmp;
}