您的位置:首页 > 其它

替换字符串中的空格

2016-01-02 23:36 169 查看
先统计总的空格数,从后往前替换#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.out

OBJ = main.o

all: $(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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  字符串