JAVA小练习89——自己实现一个trim方法(去除字符串首尾空格)

朴灿烈づ我的快乐病毒、 2022-01-25 19:47 334阅读 0赞
  1. public class Demo89 {
  2. public static void main(String[] args) {
  3. String str = " 随意 啦 ";
  4. System.out.println("字符串的内容:"+ myTrim(str));
  5. }
  6. public static String myTrim(String str){
  7. //定义两个变量记录开始于结束的索引值
  8. int startIndex = 0 ;
  9. int endIndex = str.length()-1;
  10. //确定开始的索引值
  11. while(str.charAt(startIndex)==' '){
  12. startIndex++;
  13. }
  14. //确定结束的索引值
  15. while(str.charAt(endIndex)==' '){
  16. endIndex--;
  17. }
  18. //指定索引值截取子串。
  19. String result = str.substring(startIndex, endIndex+1);
  20. return result;
  21. }
  22. }

发表评论

表情:
评论列表 (有 0 条评论,334人围观)

还没有评论,来说两句吧...

相关阅读