简体   繁体   English

如何有效替换字符串中的字符

[英]How to efficiently replace characters in a String

I have a string like this: 我有一个像这样的字符串:

String line="[x1,x2,x3]";

I want to remove both of the square brackets from the String (replace them with an empty string). 我想从字符串中删除两个方括号(用空字符串替换它们)。 I tried it like this: 我这样尝试过:

 String x=line.replace("[","").replace("]","");

Is there a more efficient way than this? 有没有比这更有效的方法?

You may use .replaceAll if you want to use a regex to remove both [ and ] at the same time anywhere inside the string (actually, the equivalent of OP two line code snippet): 如果要使用正则表达式同时删除字符串中的任何地方的 [] ,则可以使用.replaceAll (实际上,这等效于OP两行代码段):

String x = line.replaceAll("[\\]\\[]+", "");

The [\\]\\[]+ pattern matches one or more ( + ) [ or ] characters (these must be escaped inside [....] , a character class). [\\]\\[]+模式匹配一​​个或多个( +[]字符(这些字符必须在字符类[....]内转义)。

Java demo : Java演示

String line="[x1,x2,x3]";
String x = line.replaceAll("[\\[\\]]+", "");
System.out.println(x);
// => x1,x2,x3

String is immutable so you can 字符串是不可变的,因此您可以

String x = line.replace("[","").replace("]","");

another more efficient way is using regex with a pattern for both [ and ] 另一种更有效的方法是对[]使用正则表达式

like 喜欢

String x = line.replaceAll("[\\]\\[]+", "");

如果方括号始终存在,并且始终如示例所示在字符串的开头和结尾,则可以只使用substring

String x2 = line.substring(1, line.length()-1);

Another way: 其他方式:

line = line.substring(1, line.length()-1);

If you want to preserve the square brackets that comes in between, then you can use: 如果要保留介于两者之间的方括号,则可以使用:

String line="[x1,[x2],x3]";
line = line.replaceAll("^\\[(.*)\\]$", "$1");

Output 产量

x1,[x2],x3

If brackets can only appear at the beginning and at the end of the string, the fastest method (in terms of performance) would be using substring which does not involve regular expressions. 如果方括号只能出现在字符串的开头和结尾,则最快的方法(就性能而言)将使用不涉及正则表达式的substring

If brackets are guaranteed to be present: 如果保证有括号,请执行以下操作:

line = line.substring(1, line.length()-1);

If brackets are optional: 如果方括号是可选的:

int len = line.length();
int trimStart = (len > 0 && line.charAt(0) == '[') ? 1 : 0;
int trimEnd = (len > 0 && line.charAt(len-1) == ']') ? 1 : 0;
if (trimStart > 0 || trimEnd > 0) {
    line = line.substring(trimStart, len - trimEnd);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM