---
# System prepended metadata

title: '[字串反轉]'

---

# [字串反轉]

*把頭尾持續做交換，直到到最中間為止(first < last)

```
#include <stdio.h>



void swap(char* a, char* b)
{
    char temp = *a;
    *a = *b;
    *b = temp;
}

void reverse(char* first, char* last)
{
    while(first < last)
    {
        swap(first, last);
        first++;
        last--;
    }
}

int main()
{
    char str[] = "Hello World";
    reverse(&str[0], &str[10]);
    printf("%s", str);

    return 0;
}
```

```
void swap(char* s1, char* s2)
{
    char t = *s1;
    *s1 = *s2;
    *s2 = t;
}

void reverse(char* s)
{

    int n = 0;
    
    while(*(s+n)!='\0')
        n++;

    for(int i = 0; i < n/2; i++)
        swap(s+i, s+n-i-1);

}

int main()
{
    char s[] = "helloyy";
    reverse(s);
    printf("%s",s);
    

    return 0;
}
```