zoukankan      html  css  js  c++  java
  • 将一个字符串中的空格替换成“%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)
    

  • 相关阅读:
    基于Java的地铁线路查询系统设计思路
    个人总结05
    构建之法读书笔记03
    Java 8 (二) 新的时间API
    MySql基础笔记(三)其他重要的事情
    MySql基础笔记(二)Mysql语句优化---索引
    JavaScript基础笔记(十四)最佳实践
    JavaScript基础笔记(十三)测试和调试
    MySql基础笔记(一)Mysql快速入门
    JavaScript基础笔记(十二)Ajax
  • 原文地址:https://www.cnblogs.com/uncleyong/p/6898204.html
Copyright © 2011-2022 走看看