Anyone know how to do how to covert FirstName
to First Name
.
The splitting has to take place based on The Upper-Case letters , but it should exclude the first letter.
I know how to do it using split. There is any other way to do it apart from split functionality.
Not really split
, just replaceAll
:
str.replaceAll("(?!^)([A-Z])", " $1")
This solution assumes that you don't want to add space before an uppercase English alphabet if it is the first character in the string. So, " FirstName"
will become " First Name"
(note the 2 spaces).
(?!^)
is negative look-ahead (?!pattern)
, just checking this is not the beginning of the string ^
. I capture (pattern)
the uppercase English alphabet, and use the captured text in the replacement $1
($1
means whatever captured in capturing group 1 is put in the replacement string - in this case there is only 1 capturing group).
Another solution that add space before an uppercase English alphabet, only if it is preceded by lowercase English alphabet:
str.replaceAll("(?<=[a-z])([A-Z])", " $1")
(?<=[a-z])
is a positive look-behind (?<=pattern)
that checks whether the capital characters [A-Z]
is preceded by lowercase English alphabet [a-z]
. The rest has been explained above.
The pattern can vary a lot based on the requirement. You only give one example instead of concrete requirement, so I will take a wild guess and pick out a pattern for you.
6 to 11 times faster than replaceAll :
StringBuilder s = new StringBuilder( "FirstName" );
for( int i = 1; i < s.length(); ++i ) {
if( Character.isUpperCase( s.charAt( i ))) {
s.insert( i++, ' ' );
}
}
bench :
long atStart = System.currentTimeMillis();
for( int j = 0; j < 1000000; ++j ) {
StringBuilder s = new StringBuilder( "FirstName" );
for( int i = 1; i < s.length(); ++i ) {
if( Character.isUpperCase( s.charAt( i ))) {
s.insert( i++, ' ' );
}
}
}
long elapsed1 = System.currentTimeMillis() - atStart;
atStart = System.currentTimeMillis();
for( int j = 0; j < 1000000; ++j ) {
String s = "FirstName";
s = s.replaceAll("(?!^)([A-Z])", " $1");
}
long elapsed2 = System.currentTimeMillis() - atStart;
System.err.println( "Ratio: " + elapsed2 / (double)elapsed1 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With