zoukankan      html  css  js  c++  java
  • 13、请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

    请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

    思路:检测到有空格时,把数组长度增加2,空格后每个元素向后移2格

    测试代码如下:

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 #define n 5000
     4 
     5 void replaceSpace(char *str,int length) { 
     6 
     7   for(int i = 0; i < length; i ++){ 
     8           if(*(str+i) == ' '){ 
     9             length += 2; 
    10              int j = length -1; //j在字符串最后一个元素的位置
    11             while(j!=i){ 
    12                   *(str+j) = *(str+j-2); //后移两个
    13                   j--; 
    14               } 
    15              *(str+i) = '%'; 
    16               *(str+i+1) = '2'; 
    17               *(str+i+2) = '0'; 
    18           } 
    19    }
    20    for(int i=0;i<length ;i++){
    21        printf("%c",str[i]);
    22    } 
    23 
    24   }
    25 
    26   int main(){
    27      char a[n];
    28      int i;
    29      int count=0;
    30  //输入字符数组,保存在a数组中
    31      for(i=0;i<n;i++){
    32          scanf("%c",&a[i]);
    33          if(a[i]!='
    '){
    34              continue;
    35          }else break;
    36      }
    37      replaceSpace(a,i);
    38 }

  • 相关阅读:
    UVA 10618 Tango Tango Insurrection
    UVA 10118 Free Candies
    HDU 1024 Max Sum Plus Plus
    POJ 1984 Navigation Nightmare
    CODEVS 3546 矩阵链乘法
    UVA 1625 Color Length
    UVA 1347 Tour
    UVA 437 The Tower of Babylon
    UVA 1622 Robot
    UVA127-"Accordian" Patience(模拟)
  • 原文地址:https://www.cnblogs.com/olivegyr/p/7001550.html
Copyright © 2011-2022 走看看