用“ ”替代string中所有的空格
2013-02-12 21:06
183 查看
solution
如果有足够的空间,可以开辟另外一个char数组,当遇到空格时,将空格替换为"%20"然后存入数组。
char str[1000];
如果没有多余的空间,假设原str数组足够大,可以遍历str数组,求出空格的个数spaceCount,根据空格的个数算出需要增加的空间数:spaceCount*2。然后从后边遍历原数组,遇到空格时进行替换,并放入原数组的后边。
The algorithm is as follows:1. Count the number of spaces during the first scan of the string.2. Parse the string again from the end and for each character:»» If a space is encountered, store “%20”.
»» Else, store the character as it is in the newly shifted location.
假设数组在后边有足够的空间
// Assume parsed string has sufficient free space at the end
如果有足够的空间,可以开辟另外一个char数组,当遇到空格时,将空格替换为"%20"然后存入数组。
char str[1000];
如果没有多余的空间,假设原str数组足够大,可以遍历str数组,求出空格的个数spaceCount,根据空格的个数算出需要增加的空间数:spaceCount*2。然后从后边遍历原数组,遇到空格时进行替换,并放入原数组的后边。
The algorithm is as follows:1. Count the number of spaces during the first scan of the string.2. Parse the string again from the end and for each character:»» If a space is encountered, store “%20”.
»» Else, store the character as it is in the newly shifted location.
假设数组在后边有足够的空间
// Assume parsed string has sufficient free space at the end
ReplaceFun(char * str, int length) { int SpaceCount = 0, NewLength, i=0; //计算空格数目 for (i = 0; i < length; i++) { if (str[i] == ’ ‘) { SpaceCount++; } } //重新计算需要的空间数目 NewLength = length + SpaceCount * 2; Str[NewLength] = ‘\0’; //从后面开始写入新数据 for (i = length — 1; i >= 0; i--) { if (str[i] == ‘ ‘) { str[NewLength -1 ] = ‘0‘; str[NewLength -2 ] = ‘2’; str[NewLength -3 ] = ‘%’; NewLength = NewLength -3; } else { str[NewLength - 1] = str[i]; NewLength = NewLength -1; } } }
相关文章推荐
- String固定起始位置字符串反转,去除前后或所有空格
- java如何把String字符串中所有的空格和制表符(\t)替换成单个符号。
- ES _all、_source的使用——_all字段连接所有字段的值构成一个用空格(space)分隔的大string而被analyzed和index,document主体保存在_source中
- 标准c++去 string 对象 所有空格%%%%%%%%%%去 左右空格代码,在网上找半天,不如自己写的好
- python中怎么写一个替代txt文本所有回车为空格的程序 ,使文本只有了连续一行 ?
- 采用递归去掉string里面的所有空格
- 去掉string里面的所有空格
- String清楚所有的空格
- 去string左右空格
- 剔除一个string里的空格
- 将字符串中的所有空格去掉,要求时间复杂度O(N)
- stringstream读取空格作为分隔符的文件
- 输入内容(string类型的),统计字母/数字/空格的数量 [C#]
- js替换字符串中所有/全部空格
- 编程遍历页面上所有TextBox控件并给它赋值为string.Empty
- string去除2端空格
- string删除空格
- string替换所有指定字符串(C++)
- JS去掉字符串中所有空格
- 遍历页面上所有TextBox,并赋值为String.Empty(Asp.Net和WinForm)