Guava
With Guava, you can write something like this:
import com.google.common.base.*;
import com.google.common.collect.*;
//...
String doctors = "doc_vijayan,doc_zubair,doc_Raja";
Function<String,String> chopAndCap =
new Function<String,String>() {
@Override public String apply(String from) {
return from.substring(4, 5).toUpperCase()
+ from.substring(5);
}
};
Iterable<String> docs = Splitter.on(',').split(doctors);
docs = Iterables.transform(docs, chopAndCap);
doctors = Joiner.on(", ").join(docs);
System.out.println(doctors);
// Vijayan, Zubair, Raja
So the concrete logical steps are:
- Define a
Function
to perform the chop-and-cap
- Use
Splitter
to split into Iterable<String>
Iterables.transform
each element using the above Function
- Use
Joiner
to join from the transformed Iterable
back to a String
If you're comfortable with this kind of programming style, you can just assemble the entire process into one smooth operation:
System.out.println(
Joiner.on(", ").join(
Iterables.transform(
Splitter.on(',').split(doctors),
new Function<String,String>() {
@Override public String apply(String from) {
return from.substring(4, 5).toUpperCase()
+ from.substring(5);
}
}
)
)
);
// Vijayan, Zubair, Raja
Apache Commons Lang
With Apache Commons Lang, you can write something like this:
import org.apache.commons.lang.*;
//...
String doctors = "doc_vijayan,doc_zubair,doc_Raja";
String[] docs = StringUtils.split(doctors, ',');
for (int i = 0; i < docs.length; i++) {
docs[i] = StringUtils.capitalize(
StringUtils.substringAfter(docs[i], "doc_")
);
}
doctors = StringUtils.join(docs, ", ");
System.out.println(doctors);
// Vijayan, Zubair, Raja
Note that you if you have both Guava and Apache Commons Lang, you can use StringUtils.capitalize/substringAfter
in chopAndCap
function above.