题目:请实现一个函数。把字符串中的每个空格替换成“%20”
例如:hello,how are you? ----> hello,how%20are%you
Java代码实现如下:
方法一:
public class Exchange {
public String replaceSpace(String arr){
if (arr == null) return null;
StringBuffer stringBuffer = new StringBuffer();//stringbuff类是用来
for (int i = 0; i < arr.length(); i++) {
if (arr.charAt(i) == ' '){//用于返回制定索引处的字符
stringBuffer.append("%20");
}else{
stringBuffer.append(String.valueOf(arr.charAt(i)));//将字符转换处字符串
}
}
return new String(stringBuffer);
}
}
方法二:
public class Exchange {
public String replaceSpace(String arr){
if (arr == null) return null;
arr = arr.replace(" ","%20");
System.out.println(arr);
return arr;
}
}
测试代码如下:
public class Test {
public static void main(String[] args) {
String arr = "hello how are you?";
Exchange exchange = new Exchange();
System.out.println(exchange.replaceSpace(arr));
}
}
测试结果如下:
hello%20how%20are%20you?