1

我有像这样的单词序列

@ ABC
@ ABCCD
@CDSFSF
@SDDSD
@SFSFS

100000 个单词我需要代码从所有单词序列中删除 @ 符号。

4

3 回答 3

4

你可以这样做:

str = str.replaceAll("^@", "");

ideone 上的演示。

于 2013-03-02T10:15:06.700 回答
1

实现它的最快方法当然是replaceFirst方法:

String exampleValue = "@ CDSFSF";

long start = System.currentTimeMillis();
for (int i = 0; i < 100000 ; i++) {
    exampleValue.replaceFirst("^@\\s+", "");
}
long end = System.currentTimeMillis();
System.out.println(end - start);

在我的电脑上大约需要 350 毫秒。

但是replaceFirst方法为每个调用创建Pattern实例。

String exampleValue = "@ CDSFSF";
Pattern pattern = Pattern.compile("^@\\s+");
long start = System.currentTimeMillis();
for (int i = 0; i < 100000 ; i++) {
    pattern.matcher(exampleValue).replaceFirst("");
}
long end = System.currentTimeMillis();
System.out.println(end - start);

在我的电脑上大约需要 150 毫秒。快两倍以上。

但是,如果您的所有案例看起来都像“@ XXXXX”,您可以编写一个代码来查找单词中的第一个字母并在此之后获取子字符串

String exampleValue = "@ CDSFSF";

long start = System.currentTimeMillis();
for (int i = 0; i < 100000 ; i++) {
    char[] array = exampleValue.toCharArray();
    int c = 0;
    for (; c < array.length;c++) {
        if (Character.isLetter(array[c])) {
            break;
        }
    }
    exampleValue.substring(c);
}
long end = System.currentTimeMillis();
System.out.println(end - start);

在我的电脑上大约需要 30 毫秒。最快的一个。

如果我是你,我会使用Pattern类的第二种解决方案,因为它简单快捷。

于 2013-03-02T10:44:22.547 回答
0

从所有单词中删除 @

(?<=\s|^)@

所以它会是

str.replaceAll("(?<=\\s|^)@", "");
于 2013-03-02T10:17:33.573 回答