String: How to replace multiple possible characters with a single character?
JavaStringJava Problem Overview
I would like to replace all '.'
and ' '
with a '_'
but I don't like my code...
is there a more efficient way to do this than:
String new_s = s.toLowerCase().replaceAll(" ", "_").replaceAll(".","_");
?
toLowerCase() just there because I want it lower-cased as well...
Java Solutions
Solution 1 - Java
String new_s = s.toLowerCase().replaceAll("[ .]", "_");
EDIT:
replaceAll
is using regular expressions, and using .
inside a character class [ ]
just recognises a .
rather than any character.
Solution 2 - Java
s.replaceAll("[\\s\\.]", "_")
Solution 3 - Java
Use String#replace()
instead of String#replaceAll()
, you don't need regex for single-character replacement.
I created the following class to test what's faster, give it a try:
public class NewClass {
static String s = "some_string with spaces _and underlines";
static int nbrTimes = 10000000;
public static void main(String... args) {
long start = new Date().getTime();
for (int i = 0; i < nbrTimes; i++)
doOne();
System.out.println("using replaceAll() twice: " + (new Date().getTime() - start));
long start2 = new Date().getTime();
for (int i = 0; i < nbrTimes; i++)
doTwo();
System.out.println("using replaceAll() once: " + (new Date().getTime() - start2));
long start3 = new Date().getTime();
for (int i = 0; i < nbrTimes; i++)
doThree();
System.out.println("using replace() twice: " + (new Date().getTime() - start3));
}
static void doOne() {
String new_s = s.toLowerCase().replaceAll(" ", "_").replaceAll(".", "_");
}
static void doTwo() {
String new_s2 = s.toLowerCase().replaceAll("[ .]", "_");
}
static void doThree() {
String new_s3 = s.toLowerCase().replace(" ", "_").replace(".", "_");
}
}
I get the following output:
> using replaceAll() twice: 100274 > > using replaceAll() once: 24814 > > using replace() twice: 31642
Of course I haven't profiled the app for memory consumption, that might have given very different results.