请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = “We are happy.”
输出:“We%20are%20happy.”
限制:
0 <= s 的长度 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
使用StringBuilder类,创建字符序列对象,遍历字符,使用chatAt()方法对应字符索引查找单个字符,当出现的不是空格时写入当前字符至字符序列,当出现空格时写入"%20"这个字符到字符序列中,从而完成替代。
代码:
package offer_05;
public class offer_05 {
public static void main(String[] Args){
String s = "We are happy.";
System.out.println(offer_05.replaceSpace(s));
}
public static String replaceSpace(String s) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
stringBuilder.append(s.charAt(i)==' '? "%20" :s.charAt(i));
}
return stringBuilder.toString();
}
}
测试代码:
package test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import offer_05.offer_05;
import org.junit.Test;
public class offer_05Test {
@Test
public void offer_05test(){
String s = "We are happy.";
assertEquals("We%20are%20happy.", offer_05.replaceSpace(s));
}
@Test
public void offer_05test1(){
String s = " .";
assertEquals("%20%20%20.", offer_05.replaceSpace(s));
}
@Test
public void offer_05test2(){
String s = ".";
assertEquals(".", offer_05.replaceSpace(s));
}
@Test
public void offer_05test3(){
String s = " ";
assertEquals("%20", offer_05.replaceSpace(s));
}
}