4 替换空格
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
C++:
1 class Solution { 2 public: 3 void replaceSpace(char *str,int length) { 4 int blankNum = 0 ; 5 for(int i = 0 ; i < length ; i++){ 6 if (str[i] == ' ') 7 blankNum++ ; 8 } 9 int newLen = 2*blankNum+length ; 10 int p1 = length; 11 int p2 = newLen; 12 for(; p1 >= 0 && p1 < p2; p1--){ 13 if (str[p1] == ' '){ 14 str[p2--] = '0' ; 15 str[p2--] = '2' ; 16 str[p2--] = '%' ; 17 }else{ 18 str[p2--] = str[p1] ; 19 } 20 } 21 } 22 };
C++:
1 void ReplaceBlank(char ch[] , int len){ 2 if (ch == NULL || len <= 0) 3 return ; 4 int oldLen = 0 ; 5 int newLen = 0 ; 6 int blankNum = 0 ; 7 for (int i = 0; ch[i] != '\0';i++ ){ 8 oldLen++ ; 9 if (ch[i] == ' ') 10 blankNum++ ; 11 } 12 newLen = oldLen + blankNum * 2 ; 13 if (newLen > len) 14 return ; 15 int p1 = oldLen ; 16 int p2 = newLen ; 17 18 while(p1 >= 0 && p2 > p1){ 19 if (ch[p1] == ' '){ 20 ch[p2--] = '0' ; 21 ch[p2--] = '2' ; 22 ch[p2--] = '%' ; 23 }else{ 24 ch[p2--] = ch[p1] ; 25 } 26 p1-- ; 27 } 28 29 30 }
java:
1 public class Solution { 2 public String replaceSpace(StringBuffer str) { 3 int blankNum = 0 ; 4 int oldLen = str.length(); 5 for (int i = 0 ; i < oldLen ; i++){ 6 if (str.charAt(i) == ' '){ 7 blankNum++ ; 8 } 9 } 10 int newLen = 2*blankNum+oldLen ; 11 str.setLength(newLen) ; 12 int p1 = oldLen-1 ; 13 int p2 = newLen-1 ; 14 for (; p1 >= 0 && p1 < p2 ; p1--){ 15 if (str.charAt(p1) == ' '){ 16 str.setCharAt(p2--,'0') ; 17 str.setCharAt(p2--,'2') ; 18 str.setCharAt(p2--,'%') ; 19 }else{ 20 str.setCharAt(p2--,str.charAt(p1)) ; 21 } 22 } 23 return str.toString() ; 24 } 25 }
java:
1 public class Solution { 2 public String replaceSpace(StringBuffer str) { 3 int p1 = str.length()-1 ; 4 for(int i = 0 ; i <= p1 ; i++){ 5 if (str.charAt(i) == ' ') 6 str.append(" ") ; 7 } 8 int p2 = str.length()-1 ; 9 while(p1 >= 0 && p1 < p2 ){ 10 char c = str.charAt(p1--) ; 11 if (c == ' '){ 12 str.setCharAt(p2--,'0') ; 13 str.setCharAt(p2--,'2') ; 14 str.setCharAt(p2--,'%') ; 15 }else{ 16 str.setCharAt(p2--,c) ; 17 } 18 } 19 return str.toString() ; 20 } 21 }
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号