views:

87

answers:

4

I have a String str which can have list of values like below. I want the first letter in the string to be uppercase and if underscore appears in the string then i need to remove it and need to make the letter after it as upper case. The rest all letter i want it to be lower case.

""
"abc" 
"abc_def"
"Abc_def_Ghi12_abd"
"abc__de"
"_"
Output:
""
"Abc"
"AbcDef"
"AbcDefGhi12Abd"
"AbcDe"
""
+1  A: 

Well, without showing us that you put any effort into this problem this is going to be kinda vague.

I see two possibilities here:

  1. Split the string at underscores, apply the answer from this question to each part and re-combine them.
  2. Create a StringBuilder, walk through the string and keep track of whether you are

    • at the start of the string
    • after an underscore or
    • somewhere else

    and act appropriately on the current character before appending it to the StringBuilder instance.

Joey
Thanks a lot for the info
Arav
+1  A: 
  1. replace _ with space (str.replace("_", " "))
  2. use WordUtils.capitalizeFully(str); (from commons-lang)
  3. replace space with nothing (str.replace(" ", ""))
Bozho
Thanks a lot for the info
Arav
A: 

You can use following regexp based code:

public static String camelize(String input) {
  char[] c = input.toCharArray();
  Pattern pattern = Pattern.compile(".*_([a-z]).*");
  Matcher m = pattern.matcher(input);
  while ( m.find() ) {
    int index = m.start(1);
    c[index] = String.valueOf(c[index]).toUpperCase().charAt(0); 
  }
  return String.valueOf(c).replace("_", "");
}
dotsid
Thanks a lot for the info.
Arav
A: 

Use Pattern/Matcher in the java.util.regex package:

for each string that is in your array do the following:

StringBuffer output = new StringBuffer();
Matcher match = Pattern.compile("[^|_](\w)").matcher(inStr);
while(match.find()) {
   match.appendReplacement(output, matcher.match(0).ToUpper());
}
match.appendTail(output);

// Will have the properly capitalized string.
String capitalized = output.ToString();

The regular expression looks for either the start of the string or an underscore "[^|_]" Then puts the following character into a group "(\w)"

The code then goes through each of the matches in the input string capitalizing the first satisfying group.

Adrian Regan
Thanks a lot for the info
Arav