标签:c语言
------------------------------------------------------------------------------------------------------
例如:有字符串we are family,实现后的字符串为we%20are%20family。
如果从前向后,遇空格替换空格,那么family必将向后移动两次;那么我们可以从后向前实现,
先预留足够的空间,先移动family,再移动are,遇空格填充即可。
------------------------------------------------------------------------------------------------------
C语言代码:
# include <stdio.h> # include <stdlib.h> # include <string.h> # include <assert.h> # define MAX 50 void insert(char *p) { assert(p); char *pstart = NULL; char *pend = NULL; int black = 0; int size = strlen(p); pstart = p + size; while (*p) //统计预留空格数 { if (*p == ‘ ‘) { black++; } p++; } pend = pstart + (black * 2); while (pstart < pend) { if (*pstart != ‘ ‘) { *pend = *pstart; pstart--; pend--; } else { *pend-- = ‘0‘; *pend-- = ‘2‘; *pend-- = ‘%‘; *pstart--; } } } int main() { char str[MAX] = ""; printf("请输入字符串:"); gets(str); insert(str); printf("%s\n",str); system("pause"); return 0; }
------------------------------------------------------------------------------------------------------
干活小知识:循环语句,应当将最长的循环放在最内层,最短的放在最外层,以减少CPU跨切循环层数,建议for循环的循环控制变量采取“半开半闭”的写法。
------------------------------------------------------------------------------------------------------
本文出自 “无名小卒” 博客,请务必保留此出处http://814193594.blog.51cto.com/10729329/1708947
标签:c语言
原文地址:http://814193594.blog.51cto.com/10729329/1708947