#include "stdlib.h"
#include "stdio.h"
#include "string.h"
/*
* head头指针和end尾指针相向而行
* head头指针-><-end尾指针
* head头指针从前向后遍历-end尾指针从后向前遍历
* head头指针 end尾指针
* | |
* v v
* " aoe888aoe123abc "
*
*
*/
void main() {
// 去掉空格
//char* ptr = " aoe888aoe123abc ";
//char* ptr = "H aoe E";
//char* ptr = "";
//char* ptr = " ";
char* ptr = " aoe ";
// 对于字符串:n = strlen(ptr); ptr[n] 是 '\0', ptr[n-1]是最后边字符;
// head -> ptr[0];
// end -> ptr[n-1]
int count = 0;
int head, end;
head = 0;
end = strlen(ptr) -1; // 注意:从0开始,所以要长度-1
printf("ptr[end]:%c\n", ptr[end]);
printf("strlen(ptr):%d, end:%d\n", strlen(ptr), end);
while (isspace(ptr[head]) && ptr[head] != '\0') {
head++;
}
while (isspace(ptr[end]) && end > 0) {
end--;
}
//if ( end > head) { // 避免char* ptr = " "; 字符串都是空格时,end - head为负数
// count = end - head + 1;
//}
count = end - head + 1;
printf("count:%d\n", count);
system("pause");
}
字符串反转demo
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
void main() {
char ptr[] = "aoeiuv";
char tmp;
char* ptrHead = ptr;
char* ptrEnd = ptr + strlen(ptr) - 1;
while (ptrHead < ptrEnd) {
tmp = *ptrHead;
*ptrHead = *ptrEnd;
*ptrEnd = tmp;
++ptrHead;
--ptrEnd;
}
printf("%s\n", ptr);
system("pause");
}