public class Demo {
public static void main(String[] args) {
String str = " Hello world! "; //定义一个字符串,前后都有空格
int s = 0;
int l = str.length() - 1;
while(str.charAt(s) == ' ') { //如果当前位置为空格,将继续执行下去,从前往后
s++;
}
while(str.charAt(l)== ' ') { //如果当前位置为空格,将继续执行下去,从后往前
l--;
}
System.out.println(str.substring(s, l+1)); //调用字符串的一个方法,取出字符串中s到l+1位置的子字符串。
}
}
Java:删除字符串左右两端出现的空格(不用trim方法)
最新推荐文章于 2024-05-14 22:19:41 发布