• 将一个字符串中的空格替换成“%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
    ", 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]; //第一次替换的是字符串的结束符''
    43             j--;
    44             i--; 
    45         }
    46     }
    47     printf("处理后的字符串为:%s
    ", 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)
    

  • 相关阅读:
    邂逅明下(巴什博弈+hdu2897)
    抽象接口的过程小结
    线程经常使用操作
    对继承的再次理解
    阿里Java开发手冊之编程规约
    [持续更新]Windows Programming常见Hungarian Notation/Abbreviation大全
    [转]__cdecl与__stdcall
    private继承的作用
    [转]C++中的三种继承public,protected,private
    如何只利用NMAKE+CL+LINK写WIN32程序
  • 原文地址:https://www.cnblogs.com/uncleyong/p/6898204.html
Copyright © 2020-2023  润新知