剑指No2

输入一个字符串,检测字符串中的空格,并用“%20”替换掉空格

解题思路:

1.采用Stringbuffer拼接新字符串进行输出

   a.创建空串

   b.扫描输入的字符串,如果为空则该位置拼接%20,不为空原样输出

2.检测字符串中的空格,直接在空格位置直接替换

   a.遍历查找空格

   b.将空格替换成%20

 实现 1.采用Stringbuffer拼接新字符串进行输出

public static void  main(String [] args) {
String msg = "We use stringbugger for test.";
if(msg == null){
System.out.println("输入的字符串为空串");
}else{
StringBuffer str = new StringBuffer();
for(int i = 0;i<msg.length();i++){
if(msg.charAt(i) == ' '){
str.append("%20");
}else{
str.append(msg.charAt(i));
}
}
System.out.println(str);
}
}
运行结果:


实现2.检测字符串中的空格,直接在空格位置直接替换
public static void  main(String [] args) {
String str = "We are just for test.";
if (str == null) {
System.out.println("该字符串为空串。");
}else {
String result = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
result = str.replace(" ", "20%");
}
}
System.out.print(result);
}
}
运行结果:

 


猜你喜欢

转载自www.cnblogs.com/teyues/p/12895773.html
今日推荐