I have word sequences like
@ ABC
@ ABCCD
@CDSFSF
@SDDSD
@SFSFS
100000 words in number I need code to remove @ symbol from all word sequence.
I have word sequences like
@ ABC
@ ABCCD
@CDSFSF
@SDDSD
@SFSFS
100000 words in number I need code to remove @ symbol from all word sequence.
Fastest way to implement it, is of course, replaceFirst method:
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);
It takes about 350 milliseconds on my computer.
But replaceFirst method creates Pattern instance for each invoke.
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);
It takes about 150 milliseconds on my computer. More than two times faster.
But if all your cases look like "@ XXXXX" you can write a code which find first letter in the word and get substring after that:
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);
It takes about 30 milliseconds on my computer. The fastest one.
If I were you I would use second solution with Pattern class, because it simple and fast.
to remove @ from all words
(?<=\s|^)@
So it would be
str.replaceAll("(?<=\\s|^)@", "");