在 Java 中修剪字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2088037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:25:32  来源:igfitidea点击:

Trim characters in Java

javastringtrim

提问by Quintin Par

How can I trim characters in Java?
e.g.

如何在 Java 中修剪字符?
例如

String j = “\joe\jill\”.Trim(new char[] {“\”});

jshould be

j应该是

"joe\jill"

“乔\吉尔”

String j = “Hyman\joe\jill\”.Trim("Hyman");

jshould be

j应该是

"\joe\jill\"

“\乔\吉尔\”

etc

等等

采纳答案by Colin Gislason

Apache Commonshas a great StringUtils class(org.apache.commons.lang.StringUtils). In StringUtilsthere is a strip(String, String)method that will do what you want.

Apache Commons有一个很棒的StringUtils 类(org.apache.commons.lang.StringUtils)。在StringUtils有一个strip(String, String)会做你想要什么方法。

I highly recommend using Apache Commons anyway, especially the Collections and Lang libraries.

无论如何,我强烈建议使用 Apache Commons,尤其是 Collections 和 Lang 库。

回答by Adamski

EDIT: Amended by answer to replace just the first and last '\' character.

编辑:通过答案修改以仅替换第一个和最后一个 '\' 字符。

System.err.println("\joe\jill\".replaceAll("^\\|\\$", ""));

回答by Alex B

I don't think there is any built in function to trim based on a passed in string. Here is a small example of how to do this. This is not likely the most efficient solution, but it is probably fast enough for most situations, evaluate and adapt to your needs. I recommend testing performance and optimizing as needed for any code snippet that will be used regularly. Below, I've included some timing information as an example.

我认为没有任何内置函数可以根据传入的字符串进行修剪。这是一个如何做到这一点的小例子。这可能不是最有效的解决方案,但对于大多数情况,它可能足够快,评估并适应您的需求。我建议测试性能并根据需要对将经常使用的任何代码片段进行优化。下面,我以一些时序信息为例。

public String trim( String stringToTrim, String stringToRemove )
{
    String answer = stringToTrim;

    while( answer.startsWith( stringToRemove ) )
    {
        answer = answer.substring( stringToRemove.length() );
    }

    while( answer.endsWith( stringToRemove ) )
    {
        answer = answer.substring( 0, answer.length() - stringToRemove.length() );
    }

    return answer;
}

This answer assumes that the characters to be trimmed are a string. For example, passing in "abc" will trim out "abc" but not "bbc" or "cba", etc.

此答案假定要修剪的字符是字符串。例如,传入“abc”将修剪掉“abc”而不是“bbc”或“cba”等。

Some performance times for running each of the following 10 million times.

运行以下 1000 万次的某些性能时间。

" mile ".trim();runs in 248 ms included as a reference implementation for performance comparisons.

" mile ".trim();在 248 毫秒内运行,作为性能比较的参考实现。

trim( "smiles", "s" );runs in 547 ms - approximately 2 times as long as java's String.trim()method.

trim( "smiles", "s" );运行时间为 547 毫秒 - 大约是 javaString.trim()方法的2 倍。

"smiles".replaceAll("s$|^s","");runs in 12,306 ms - approximately 48 times as long as java's String.trim()method.

"smiles".replaceAll("s$|^s","");运行时间为 12,306 毫秒 - 大约是 javaString.trim()方法的48 倍。

And using a compiled regex pattern Pattern pattern = Pattern.compile("s$|^s");pattern.matcher("smiles").replaceAll("");runs in 7,804 ms - approximately 31 times as long as java's String.trim()method.

使用编译的正则表达式模式Pattern pattern = Pattern.compile("s$|^s");pattern.matcher("smiles").replaceAll("");运行时间为 7,804 毫秒 - 大约是 javaString.trim()方法的31 倍。

回答by Ahmed Kotb

it appears that there is no ready to use java api that makes that but you can write a method to do that for you. this linkmight be usefull

似乎还没有准备好使用 java api 来实现这一点,但您可以编写一种方法来为您做到这一点。这个链接可能有用

回答by Paulo Guedes

This does what you want:

这做你想要的:

public static void main (String[] args) {
    String a = "\joe\jill\";
    String b = a.replaceAll("\\$", "").replaceAll("^\\", "");
    System.out.println(b);
}

The $is used to remove the sequence in the end of string. The ^is used to remove in the beggining.

$用于去除在字符串的末尾序列。将^用于在beggining删除。

As an alternative, you can use the syntax:

作为替代方案,您可以使用以下语法:

String b = a.replaceAll("\\$|^\\", "");

The |means "or".

|手段“或”。

In case you want to trim other chars, just adapt the regex:

如果您想修剪其他字符,只需调整正则表达式:

String b = a.replaceAll("y$|^x", ""); // will remove all the y from the end and x from the beggining

回答by Valentin Rocher

You could use removeStartand removeEndfrom Apache Commons Lang StringUtils

您可以使用removeStartremoveEnd来自 Apache Commons Lang StringUtils

回答by OscarRyz

Hand made for the first option:

第一个选项的手工制作:

public class Rep {
    public static void main( String [] args ) {
       System.out.println( trimChar( '\' , "\\\joe\jill\\\\" )  ) ;
       System.out.println( trimChar( '\' , "joe\jill" )  ) ;
    }
    private static String trimChar( char toTrim, String inString ) { 
        int from = 0;
        int to = inString.length();

        for( int i = 0 ; i < inString.length() ; i++ ) {
            if( inString.charAt( i ) != toTrim) {
                from = i;
                break;
            }
        }
        for( int i = inString.length()-1 ; i >= 0 ; i-- ){ 
            if( inString.charAt( i ) != toTrim ){
                to = i;
                break;
            }
        }
        return inString.substring( from , to );
    }
}

Prints

印刷

joe\jil

joe\jil

joe\jil

joe\jil

回答by x4u

I would actually write my own little function that does the trick by using plain old char access:

我实际上会编写我自己的小函数,通过使用普通的旧字符访问来解决这个问题:

public static String trimBackslash( String str )
{
    int len, left, right;
    return str == null || ( len = str.length() ) == 0 
                           || ( ( left = str.charAt( 0 ) == '\' ? 1 : 0 ) |
           ( right = len > left && str.charAt( len - 1 ) == '\' ? 1 : 0 ) ) == 0
        ? str : str.substring( left, len - right );
}

This behaves similar to what String.trim() does, only that it works with '\' instead of space.

这与 String.trim() 的行为类似,只是它使用 '\' 而不是空格。

Here is one alternative that works and actually uses trim(). ;) Althogh it's not very efficient it will probably beat all regexp based approaches performance wise.

这是一种有效且实际使用trim()的替代方法。;) 尽管它的效率不是很高,但它可能会在性能方面击败所有基于正则表达式的方法。

String j = “\joe\jill\”;
j = j.replace( '\', '\f' ).trim().replace( '\f', '\' );

回答by Cowan

CharMatcher– Google Guava

CharMatcher– 谷歌番石榴

In the past, I'd second Colins' Apache commons-lang answer. But now that Google's guava-librariesis released, the CharMatcherclass will do what you want quite nicely:

在过去,我会第二个柯林斯的 Apache commons-lang answer。但是现在 Google 的guava-libraries发布了,CharMatcher类将很好地完成您想要的操作:

String j = CharMatcher.is('\').trimFrom("\joe\jill\"); 
// j is now joe\jill

CharMatcherhas a very simple and powerful set of APIs as well as some predefined constants which make manipulation very easy. For example:

CharMatcher有一组非常简单和强大的 API 以及一些预定义的常量,这使得操作非常容易。例如:

CharMatcher.is(':').countIn("a:b:c"); // returns 2
CharMatcher.isNot(':').countIn("a:b:c"); // returns 3
CharMatcher.inRange('a', 'b').countIn("a:b:c"); // returns 2
CharMatcher.DIGIT.retainFrom("a12b34"); // returns "1234"
CharMatcher.ASCII.negate().removeFrom("a??b"); // returns "ab";

Very nice stuff.

很不错的东西。

回答by Lawrence Dol

Here's how I would do it.

这是我将如何做到的。

I think it's about as efficient as it reasonably can be. It optimizes the single character case and avoids creating multiple substrings for each subsequence removed.

我认为它的效率是合理的。它优化了单个字符的大小写并避免为每个删除的子序列创建多个子字符串。

Note that the corner case of passing an empty string to trim is handled (some of the other answers would go into an infinite loop).

请注意,处理将空字符串传递给修剪的极端情况(其他一些答案将进入无限循环)。

/** Trim all occurrences of the string <code>rmvval</code> from the left and right of <code>src</code>.  Note that <code>rmvval</code> constitutes an entire string which must match using <code>String.startsWith</code> and <code>String.endsWith</code>. */
static public String trim(String src, String rmvval) {
    return trim(src,rmvval,rmvval,true);
    }

/** Trim all occurrences of the string <code>lftval</code> from the left and <code>rgtval</code> from the right of <code>src</code>.  Note that the values to remove constitute strings which must match using <code>String.startsWith</code> and <code>String.endsWith</code>. */
static public String trim(String src, String lftval, String rgtval, boolean igncas) {
    int                                 str=0,end=src.length();

    if(lftval.length()==1) {                                                    // optimize for common use - trimming a single character from left
        char chr=lftval.charAt(0);
        while(str<end && src.charAt(str)==chr) { str++; }
        }
    else if(lftval.length()>1) {                                                // handle repeated removal of a specific character sequence from left
        int vallen=lftval.length(),newstr;
        while((newstr=(str+vallen))<=end && src.regionMatches(igncas,str,lftval,0,vallen)) { str=newstr; }
        }

    if(rgtval.length()==1) {                                                    // optimize for common use - trimming a single character from right
        char chr=rgtval.charAt(0);
        while(str<end && src.charAt(end-1)==chr) { end--; }
        }
    else if(rgtval.length()>1) {                                                // handle repeated removal of a specific character sequence from right
        int vallen=rgtval.length(),newend;
        while(str<=(newend=(end-vallen)) && src.regionMatches(igncas,newend,rgtval,0,vallen)) { end=newend; }
        }

    if(str!=0 || end!=src.length()) {
        if(str<end) { src=src.substring(str,end); }                            // str is inclusive, end is exclusive
        else        { src="";                     }
        }

    return src;
    }