【问题标题】:how do you use string.trim() method to trim the white spaces only at the end? [duplicate]您如何使用 string.trim() 方法仅在最后修剪空格? [复制]
【发布时间】:2013-07-30 11:29:01
【问题描述】:

如何使用 string.trim() 方法仅在末尾修剪空白?

我的意思是不影响前面的空间

例如:输入:“这是链接的” o/p : "这是链接的"

【问题讨论】:

标签: java .net string c#-4.0


【解决方案1】:

使用正则表达式:

str.replaceAll("\\s+$", "");
  1. \s – 任何空白字符

  2. + – 匹配一个或多个空白字符

  3. $ – 在字符串的末尾

您可以从here阅读更多内容。

【讨论】:

  • +1 解释正则表达式
【解决方案2】:

没有右修剪方法,但您可以通过多种变通方法来实现。 一种包括在字符串的开头放置一个非空白字符,修剪它,然后删除该字符。使用 String.replaceAll() 将允许您使用正则表达式来完成。

【讨论】:

    【解决方案3】:

    我相信你不能用 trim() 做到这一点。也许你可以寻找具有实用方法 StringUtils#stripEnd() 的 Apache commons。

    我尚未对此进行测试,但希望它适用于您的目的:

    string = string.replaceAll("\\s+$", "");  
    

    另一种解决方案是遍历从反向字符串中获得的char[] 并删除不需要的字符!

    【讨论】:

      【解决方案4】:

      试试这个正则表达式

          str = str.replaceAll("(.+?) +", "$1");
      

      【讨论】:

        【解决方案5】:

        如果您必须使用 trim() 方法,那么这可能会有所帮助:-

        public class OP2 {
           public static void main(String[] s) {
              //object hash table 
               int index = 0;
               String s1 = "  sdfwf   ";
               for(int i=0;i<s1.length();i++)
               {
                   if(s1.charAt(i)==' ')
                       index = index + 1;
                   else 
                       break;
               }
               System.out.println(s1.substring(0,index)+ s1.trim());
        
           }
        }
        

        【讨论】:

          【解决方案6】:

          如果查询是针对 .net 语言的,那么您可以使用内置的 RTRIM 方法来实现。

          【讨论】:

            【解决方案7】:

            在 .NET/C# 中,您可以在字符串对象上使用 TrimEnd 方法:

            " this is linkedin ".TrimEnd();

            【讨论】:

              【解决方案8】:
              public class RegexRemoveEnd {   
                  public static String removeTrailingSpaces(String text) {
                      return text.replaceAll(" +$", "");
                  }
              }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2011-04-17
                • 1970-01-01
                • 2013-11-16
                • 2012-03-07
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多