替换字符串中的空格
来源:互联网 发布:金融工程就业前景知乎 编辑:程序博客网 时间:2024/05/16 11:42
先统计总的空格数,从后往前替换
#include <stdio.h> #include <stdlib.h>#include <string.h>/* 将字符串中的空格替换为"%20", len为字符串可容纳的最大长度 */char *replace_blank(char *str, int len){int new_len = 0;//替换后的总长度int real_len = 0;//替换前字符串的真实长度int blank_count = 0;//字符串中空格个数int index_new = 0;//替换后字符串的当前索引int index_old = 0;//替换前字符串的当前索引int i = 0;if(!str || len <= 0){return NULL;}while(str[i]){if(str[i] == ' '){blank_count++;}real_len++;i++;}new_len = real_len + blank_count*2;if(new_len >= len){return NULL;}index_new = new_len - 1;index_old = real_len - 1;while(index_old >= 0){if(str[index_old] == ' '){index_old--;str[index_new--] = '0';str[index_new--] = '2';str[index_new--] = '%';}else{str[index_new--] = str[index_old--];}}return str;}int main(int argc, char *argv[]){char *str = NULL;str = malloc(1024*1024);if(!str)return -1;if(argc >= 2){strcpy(str, argv[1]);printf("src str: %s\n", str);printf("dst str: %s\n", replace_blank(str, 1024*1024));}return 0;}
测试用例
TARGET = a.outOBJ = main.oall: $(OBJ)gcc -o $(TARGET) $(OBJ)./$(TARGET) "21314"./$(TARGET) ""./$(TARGET) " "./$(TARGET) " "./$(TARGET) " 12 2 4"./$(TARGET) " 12 2 4 "./$(TARGET) " fasfasf qw"%.o: %.c gcc -Wall -Werror -g -MMD -c $< clean:-rm $(OBJ) $(OBJ:%.o=%.d) a.out-include $(OBJ:%.o=%.d).PHONY: all clean
0 0
- 替换字符串中的空格
- 替换字符串中的空格
- 替换字符串中的空格
- 替换字符串中的空格
- 替换字符串中的空格
- 替换字符串中的空格
- 字符串中的替换空格
- 替换字符串中的空格
- 字符串中的空格替换
- 替换字符串中的空格
- 字符串中的空格替换
- 替换字符串中的空格
- 替换字符串中的空格
- 替换字符串中的空格
- 替换字符串中的空格
- 替换字符串中的空格
- 替换字符串中的空格
- 替换字符串中的空格
- 动画封装二:实现水平缓动运动
- QQ游戏百万人同时在线服务器架构实现
- 云计算技术图谱
- Git 本地操作
- hdu2030汉字统计
- 替换字符串中的空格
- redis集群环境搭建以及java中jedis客户端集群代码实现
- 【15】Session
- Java 创建多线程
- AVFoundation和GPUImage初探
- 多个字段 按要求的字段排序
- Hadoop集群安装过程详细记录
- lruCache
- Android应用性能优化的小技巧