weixin_51573847 2022-10-31 10:44 采纳率: 77.3%
浏览 57
已结题

java实现去除字符串空格

java trim方法用递归去除字符串前后的空格.如果传入的是null,则会返回null,如果传入的是空字符串,则会返回空字符串,如图所示.

img

  • 写回答

4条回答 默认 最新

  • 游一游走一走 2022-10-31 11:07
    关注
    package com.example.demo003.controller;
    
    public class Test03 {
        public static String trim(String s) {
            if (s == null && "".equals(s)) {
                return s;
            }
            if (!s.startsWith(" ") && !s.endsWith(" "))
                return s;
            if (s.startsWith(" ")) {
                return trim(s.substring(1));
            }
            if (s.endsWith(" ")) {
                return trim(s.substring(0, s.length() - 1));
            }
            return null;
        }
    
        public static void main(String[] args) {
            System.out.println(trim(" hello "));
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 11月8日
  • 已采纳回答 10月31日
  • 修改了问题 10月31日
  • 创建了问题 10月31日