【问题标题】:how to only trim the blanks in the beginning of a string如何只修剪字符串开头的空格
【发布时间】:2014-05-04 17:37:15
【问题描述】:

Java 方法:String.trim() 修剪字符串开头和结尾的空白(空格、换行等)。

如何只修剪字符串开头的空格?

【问题讨论】:

  • 注意:trim() 不会修剪所有空白,它会修剪characters < space,其中包括相当多的非空白。

标签: java string trim


【解决方案1】:

你可以这样做:

myString = myString.replaceAll("^\\s+", "")

如果您只想删除特定的空格(例如,仅空格),您可以将 \\s 替换为特定字符(例如:"^ +" 仅用于空格)或字符类(例如:"^[ \\t]+"用于空格和制表符)。

编辑根据@Pshemo的说法,你可以用replaceFirst代替replaceAll

【讨论】:

  • \\s 还包含行分隔符 \n \rreplaceFirst 也足够了 :)
  • @Pshemo 我不记得了,所以我添加了它们。编辑删除。谢谢。
【解决方案2】:

也试试这个

修剪开头

myString.replaceAll("^\\s+", "");

并修剪尾随

myString.replaceAll("\\s+$", "");

【讨论】:

  • 感谢您提及尾随。超出我的预期。
【解决方案3】:

如果你想给出自己的实现,那么你可以使用这样的方法-

package com.kvvssut.misc;

public class TrimAtFirst {

    public static void main(String[] args) {
        System.out.println(trimAtFirst("      \n   \r   \t  You need to trim only before spaces!    "));
    }

    private static String trimAtFirst(String string) {

        int start = 0;
        int len = string.length();

        for (; start < len; start++) {
            char ch = string.charAt(start);
            if (ch != ' ') {
                if (!(ch == '\n' || ch == '\t' || ch == '\r')) {    // include others- I am not sure if more. Also, you can customize based on your needs!
                    break;
                }
            }
        }

        return string.substring(start, len);
    }

}

输出-“您只需要在空格之前修剪!”

【讨论】:

    【解决方案4】:

    删除前导空格:

    str = str.replaceFirst("\\s+","");
    

    【讨论】:

      猜你喜欢
      • 2011-03-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-16
      • 2010-10-20
      • 2021-05-20
      • 1970-01-01
      相关资源
      最近更新 更多