We could use two pointers or indices point to head and tail of the string respectively.
Algorithm
While head is less than tail,
swapping the head and tail elements, narrowing the head and tail, and repeat the process.
/*Description: String reversing
array, pointer
Author: Liutong Xu
*/
#include<stdio.h>
#define LSIZE 81
void strRev(char s[LSIZE]);
void strRevP(char *s);
int main()
{
char str[LSIZE]="Welcome to Beijing!";
//printf("Enter string: ");
//fgets(str, LSIZE, stdin);
printf("string is %s\n",str);
strRevP(str);
printf("\nafter reverse\n");
printf("string is %s\n",str);
return 0;
}
void strRev(char s[LSIZE])
{
char stemp;
int len=0;
int i;
while (s[len]) //same as s[len]!='\0'
len++;
len--;
//len points to the last char in the string s;
for (i=0;i<=len/2;i++)
{
stemp = s[i];
s[i] = s[len-i];
s[len-i] = stemp;
}
}
void strRevP(char *s)
{
char stemp;
char *ep;
ep = s;
while (*ep)
ep++;
ep--; //end points to the last char in the string s;
while (s<ep)
{
stemp = *s;
*s = *ep;
*ep = stemp;
s++;
ep--;
}
}
stdout
string is Welcome to Beijing!
after reverse
string is !gnijieB ot emocleW
Techniquically, we designed two way to do string reverse:
1, array element processing, see strRev()
2, pointer processing, see strRevP()