标签:字符 set space class tchar while event code for
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
https://www.nowcoder.com/questionTerminal/4060ac7e3e404ad1a894ef3e17650423
1 public class Solution { 2 public String replaceSpace(StringBuffer str) { 3 int n = str.length(); 4 int sum = 0; 5 for (int i = 0; i < n; ++i) { 6 if (str.charAt(i) == ‘ ‘) sum++; 7 } 8 System.out.println(n); 9 str.setLength(n + sum * 2); 10 11 int i = n - 1, j = i + sum * 2; 12 while (i >= 0) { 13 if (str.charAt(i) == ‘ ‘) { 14 str.setCharAt(j--, ‘0‘); 15 str.setCharAt(j--, ‘2‘); 16 str.setCharAt(j--, ‘%‘); 17 i--; 18 19 } else { 20 str.setCharAt(j, str.charAt(i)); 21 j--;i--; 22 23 } 24 25 } 26 return str.toString(); 27 } 28 }
标签:字符 set space class tchar while event code for
原文地址:https://www.cnblogs.com/hyxsolitude/p/12238694.html