将一个字符串中的空格替换成“%20”(C、Python)

将一个字符串中的空格替换成“%20”

C语言:

 1 /*
 2 -----------------------------------
 3 通过函数调用,传地址来操作字符串
 4 1.先计算出替换后的字符串的长度
 5 2.从字符串最后一个字符串开始往右移
 6 -----------------------------------
 7 */
 8 
 9 
10 # include <stdio.h>
11 # include <string.h>
12 
13 void replace(char * arr)
14 {
15     int i, j, len, count;
16     count = 0;
17     len = strlen(arr);
18     
19     for (i=0; i<len; i++)
20     {
21         if (arr[i] == ' ')
22         {
23             count++; 
24         }  
25     }
26 
27     i = len;
28     j = 2 * count + len; //每一个空格用三个字符替换,所以相当于每个空格多2个字符;
29     printf("处理前的字符串为:%s\n", arr);
30 
31     while (i!=j && i>=0)
32     {
33         if (arr[i] == ' ')
34         {
35             arr[j--] = '0';
36             arr[j--] = '2';
37             arr[j--] = '%';
38             i--;
39         }
40         else
41         {
42             arr[j] = arr[i]; //第一次替换的是字符串的结束符'\0'
43             j--;
44             i--; 
45         }
46     }
47     printf("处理后的字符串为:%s\n", arr);
48 }
49 
50 int main(void)
51 {
52     char str[] = "We Are Happy.";
53     replace(str);    
54 
55     return 0; 
56 }
57 
58 /*
59 在Vc++6.0中的输出结果为:
60 -----------------------------------
61 处理前的字符串为:We Are Happy.
62 处理后的字符串为:We%20Are%20Happy.
63 Press any key to continue
64 -----------------------------------
65 */

 

另外,在C中,计算数组中元素个数用sizeof

int a[] = {1, 3, 5, 6, 9};

int m = sizeof(a)/sizeof(int);

 

Python:

如果需要修改字符串,则先转换为列表,最后再通过join转为字符串

方法一:

s = 'hello my baby'
def rep(s):
    li = []
    for i in s:
        li.append(i)
    for i in range(len(li)):
        if li[i] == ' ':
            li[i] = '%20'
    return ''.join(li)
s = rep(s)
print(s)

方法二:

s = 'hello my baby'
def rep(s):
    li = []
    for i in s:
        li.append(i)
    for i in li:
        if i==' ':
            li[li.index(i)]='%20'
    return ''.join(li)
s = rep(s)
print(s)

转载于:https://www.cnblogs.com/uncleyong/p/6898204.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值