修剪Java中的字符

我如何修剪Java中的字符?
例如

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

j应该是

“乔\吉尔”

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

j应该是

“\乔\吉尔\”

等等

Apache Commons有一个很棒的StringUtils类 。 在StringUtils有一个strip(String, String)方法,可以做你想做的事情。

我强烈推荐使用Apache Commons,特别是Collections和Lang库。

这就是你想要的:

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

$用于删除string结尾的序列。 ^用于在开始时删除。

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

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

| 意思是“或”。

如果你想修剪其他字符,只适应正则expression式:

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

CharMatcher – Google Guava

在过去,我会再次考林斯的阿帕奇普朗朗答案 。 但是现在谷歌的番石榴图书馆已经发布了, CharMatcher课程将会很好地做你想做的事情:

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

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"; 

非常好的东西。

这里是另一个非正则expression式,非超级非常好,非超级优化,但是非常容易理解的非外部lib解决scheme:

 public static String trimStringByString(String text, String trimBy) { int beginIndex = 0; int endIndex = text.length(); while (text.substring(beginIndex, endIndex).startsWith(trimBy)) { beginIndex += trimBy.length(); } while (text.substring(beginIndex, endIndex).endsWith(trimBy)) { endIndex -= trimBy.length(); } return text.substring(beginIndex, endIndex); } 

用法:

 String trimmedString = trimStringByString(stringToTrim, "/"); 

你可以使用Apache Commons Lang StringUtils中的 removeStartremoveStart

看起来没有准备好使用的Java API,但你可以写一个方法来为你做。 这个链接可能是有用的

编辑 :通过回答修改只是第一个和最后一个'\'字符。

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

手工制作的第一个选项:

 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 ); } } 

打印

joe\jil

joe\jil

我实际上写了我自己的小函数,通过使用普通的旧字符访问做伎俩:

 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 ); } 

这与String.trim()所做的行为相似,只是它与“\”而不是空格一起工作。

这是一个替代scheme,实际上使用trim()。 ;)虽然它不是非常高效,但它可能会击败所有基于正则expression式的方法。

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

我不认为有任何内置函数来修剪基于传入的string。 这是一个如何做到这一点的小例子。 这不太可能是最有效的解决scheme,但对于大多数情况来说,这可能足够快,评估和适应您的需求。 我build议testing性能并根据需要进行优化,以便定期使用任何代码片段。 下面我以一些时间信息为例。

 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; } 

这个答案假定要修剪的字符是一个string。 例如,传入“abc”将删除“abc”而不是“bbc”或“cba”等。

一些性能时间运行以下每一千万次。

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

trim( "smiles", "s" ); 运行在547毫秒 – 约为java的String.trim()方法的2倍。

"smiles".replaceAll("s$|^s",""); 运行12,306毫秒 – 大约是Java的String.trim()方法的48倍。

并使用编译的正则expression式模式Pattern pattern = Pattern.compile("s$|^s"); pattern.matcher("smiles").replaceAll(""); 运行在7,804毫秒 – 大约是java的String.trim()方法的31倍。

这是我该怎么做的。

我认为它的效率可以合理。 它优化了单个字符的情况,并避免为每个删除的子序列创build多个子string。

请注意,传递一个空string修剪处理(其他一些答案将进入一个无限循环)的angular落情况。

 /** 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; } 
 public static String trim(String value, char c) { if (c <= 32) return value.trim(); int len = value.length(); int st = 0; char[] val = value.toCharArray(); /* avoid getfield opcode */ while ((st < len) && (val[st] == c)) { st++; } while ((st < len) && (val[len - 1] == c)) { len--; } return ((st > 0) || (len < value.length())) ? value.substring(st, len) : value; }