替换一个字符数组中的所有空格符为“%20”

public void replaceBlank(char string[],int length){

//防错处理
  if(string == null || length<=0)
    return;
//第一遍遍历,统计字符长度和空格数
  int orignel_length=0;
  int countBlank = 0;
  int i=0;
  while(string[i] != '\0'){
    orignel_length++;
    if(string[i] == ' '){
    countBlank++;
    }
  i++;
  }

//计算替换后的长度
//参数中的length指的string的最大长度,如果超出长度就直接返回
  int newLength = orignel_length +countBlank*2;
  if(newLength > length)
    return;

//从后往前遇到空格替换,非空格复制
  int indexOfNew = newLength;
  int indexOfOrignel = orignel_length;
  while(indexOfNew > indexOfOrignel && indexOfOrignel >= 0){
    if(string[indexOfOrignel] == ' '){
    string[indexOfNew--]='0';
    string[indexOfNew--]='2';
    string[indexOfNew--]='%';
    }else{
      string[indexOfNew--]=string[indexOfOrignel];
    }
  indexOfOrignel--;
  }
}

 

 

做很多题的时候,正面去想可能很有难度,那么就反过来想。

posted @ 2017-04-19 18:09  HeLing_CC  阅读(312)  评论(0编辑  收藏  举报