请实现一个函数,将一个字符串s中的每个空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
数据范围:。保证字符串中的字符为大写英文字母、小写英文字母和空格中的一种。
public String replaceSpace (String s) { // write code here String str = s.replace(" ","%20"); return str; }
public String replaceSpace (String s) { // write code here String[] split = s.split(""); String s2 = ""; for (String str : split) { if (str.equals(" ")) { str = "%20"; } s2 += str; } return s2; }方法很多,直接拼接也是可以的
public String replaceSpace(String s) { // calculate space's number int space_number = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == ' ') { space_number++; } } char[] res = new char[s.length() + space_number * 2]; int res_cur_loc = 0; for (int i = 0; i < s.length(); i++) { if(s.charAt(i) == ' ') { res[res_cur_loc++] = '%'; res[res_cur_loc++] = '2'; res[res_cur_loc++] = '0'; } else { res[res_cur_loc++] = s.charAt(i); } } return new String(res); }
public String replaceSpace(String s) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == ' ') stringBuilder.append("%20"); else stringBuilder.append(s.charAt(i)); } return stringBuilder.toString(); }
import java.util.*; public class Solution { public String replaceSpace (String s) { String str = ""; for (int i = 0; i < s.length(); i++) { String str2 = s.substring(i,i+1); if (str2.equals(" ")) { str2 = "%20"; str += str2; } else { str += str2; } } return str; } }