The title pretty much says it all. What's the simplest/most elegant way that I can convert, in Java, a string from the format "THIS_IS_AN_EXAMPLE_STRING" to the format "ThisIsAnExampleString"? I figure there must be at least one way to do it using String.replaceAll() and a regex.
My initial thoughts are: prepend the string with an underscore (_), convert the whole string to lower case, and then use replaceAll to convert every character preceded by an underscore with its uppercase version.
Another option is using Google Guava's com.google.common.base.CaseFormat
George Hawkins left a comment with this example of usage:
CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "THIS_IS_AN_EXAMPLE_STRING");
Take a look at WordUtils in the Apache Commons lang library:
Specifically, the capitalizeFully(String str, char[] delimiters) method should do the job:
String blah = "LORD_OF_THE_RINGS";
assertEquals("LordOfTheRings", WordUtils.capitalizeFully(blah, '_').replaceAll("_", ""));
Green bar!
static String toCamelCase(String s){
String[] parts = s.split("_");
String camelCaseString = "";
for (String part : parts){
camelCaseString = camelCaseString + toProperCase(part);
}
return camelCaseString;
}
static String toProperCase(String s) {
return s.substring(0, 1).toUpperCase() +
s.substring(1).toLowerCase();
}
Note: You need to add argument validation.
With Apache Commons Lang3 lib is it very easy.
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
public String getName(String text) {
return StringUtils.remove(WordUtils.capitalizeFully(text, '_'), "_");
}
Example:
getName("SOME_CONSTANT");
Gives:
"SomeConstant"
Here is a code snippet which might help:
String input = "ABC_DEF";
StringBuilder sb = new StringBuilder();
for( String oneString : input.toLowerCase().split("_") )
{
sb.append( oneString.substring(0,1).toUpperCase() );
sb.append( oneString.substring(1) );
}
// sb now holds your desired String
Java 1.8 example using Streams
String text = "THIS_IS_SOME_TEXT";
String bactrianCamel = Stream.of(text.split("[^a-zA-Z0-9]"))
.map(v -> v.substring(0, 1).toUpperCase() + v.substring(1).toLowerCase())
.collect(Collectors.joining());
String dromedaryCamel = bactrianCamel.toLowerCase().substring(0, 1) + bactrianCamel.substring(1);
System.out.printf("%s is now %s%n", text, dromedaryCamel);
THIS_IS_SOME_TEXT is now thisIsSomeText
public static void main(String[] args) {
String start = "THIS_IS_A_TEST";
StringBuffer sb = new StringBuffer();
for (String s : start.split("_")) {
sb.append(Character.toUpperCase(s.charAt(0)));
if (s.length() > 1) {
sb.append(s.substring(1, s.length()).toLowerCase());
}
}
System.out.println(sb);
}
The Apache Commons project does now have the CaseUtils class, which has a toCamelCase method that does exactly as OP asked:
CaseUtils.toCamelCase("THIS_IS_AN_EXAMPLE_STRING", true, '_');
Sorry for mine five cents, I think in java too many words))
I just wondering. Why is the regexp engine in java not so familiar with lambdas as in JS((
Anyway. With java 8+ construction appears in my mind:
Arrays.stream("THIS_IS_AN_EXAMPLE_STRING".split("_"))
.collect(StringBuilder::new,
(result, w) -> result
.append(w.substring(0, 1).toUpperCase())
.append(w.substring(1).toLowerCase()),
StringBuilder::append)
.toString())
If you care about memory consumption, the below code care about it:
"THIS_IS_AN_EXAMPLE_STRING".chars().collect(StringBuilder::new,
(result, c) -> {
// Detect place for deal with
if (result.length() > 0 && result.charAt(result.length() - 1) == '_') {
result.setCharAt(result.length() - 1,
Character.toUpperCase((char) c));
} else if (result.length() > 0) {
result.append(Character.toLowerCase((char) c));
} else {
result.append(Character.toUpperCase((char) c));
}
}, StringBuilder::append).toString()
You can use org.modeshape.common.text.Inflector.
Specifically:
String camelCase(String lowerCaseAndUnderscoredWord,
boolean uppercaseFirstLetter, char... delimiterChars)
By default, this method converts strings to UpperCamelCase.
Maven artifact is: org.modeshape:modeshape-common:2.3.0.Final
on JBoss repository: https://repository.jboss.org/nexus/content/repositories/releases
Here's the JAR file: https://repository.jboss.org/nexus/content/repositories/releases/org/modeshape/modeshape-common/2.3.0.Final/modeshape-common-2.3.0.Final.jar
Not sure, but I think I can use less memory and get dependable performance by doing it char-by-char. I was doing something similar, but in loops in background threads, so I am trying this for now. I've had some experience with String.split being more expensive then expected. And I am working on Android and expect GC hiccups to be more of an issue then cpu use.
public static String toCamelCase(String value) {
StringBuilder sb = new StringBuilder();
final char delimChar = '_';
boolean lower = false;
for (int charInd = 0; charInd < value.length(); ++charInd) {
final char valueChar = value.charAt(charInd);
if (valueChar == delimChar) {
lower = false;
} else if (lower) {
sb.append(Character.toLowerCase(valueChar));
} else {
sb.append(Character.toUpperCase(valueChar));
lower = true;
}
}
return sb.toString();
}
A hint that String.split is expensive is that its input is a regex (not a char like String.indexOf) and it returns an array (instead of say an iterator because the loop only uses one things at a time). Plus cases like "AB_AB_AB_AB_AB_AB..." break the efficiency of any bulk copy, and for long strings use an order of magnitude more memory then the input string.
Whereas looping through chars has no canonical case. So to me the overhead of an unneeded regex and array seems generally less preferable (then giving up possible bulk copy efficiency). Interested to hear opinions / corrections, thanks.
public String withChars(String inputa) {
String input = inputa.toLowerCase();
StringBuilder sb = new StringBuilder();
final char delim = '_';
char value;
boolean capitalize = false;
for (int i=0; i<input.length(); ++i) {
value = input.charAt(i);
if (value == delim) {
capitalize = true;
}
else if (capitalize) {
sb.append(Character.toUpperCase(value));
capitalize = false;
}
else {
sb.append(value);
}
}
return sb.toString();
}
public String withRegex(String inputa) {
String input = inputa.toLowerCase();
String[] parts = input.split("_");
StringBuilder sb = new StringBuilder();
sb.append(parts[0]);
for (int i=1; i<parts.length; ++i) {
sb.append(parts[i].substring(0,1).toUpperCase());
sb.append(parts[i].substring(1));
}
return sb.toString();
}
Times: in milli seconds.
Iterations = 1000
WithChars: start = 1379685214671 end = 1379685214683 diff = 12
WithRegex: start = 1379685214683 end = 1379685214712 diff = 29
Iterations = 1000
WithChars: start = 1379685217033 end = 1379685217045 diff = 12
WithRegex: start = 1379685217045 end = 1379685217077 diff = 32
Iterations = 1000
WithChars: start = 1379685218643 end = 1379685218654 diff = 11
WithRegex: start = 1379685218655 end = 1379685218684 diff = 29
Iterations = 1000000
WithChars: start = 1379685232767 end = 1379685232968 diff = 201
WithRegex: start = 1379685232968 end = 1379685233649 diff = 681
Iterations = 1000000
WithChars: start = 1379685237220 end = 1379685237419 diff = 199
WithRegex: start = 1379685237419 end = 1379685238088 diff = 669
Iterations = 1000000
WithChars: start = 1379685239690 end = 1379685239889 diff = 199
WithRegex: start = 1379685239890 end = 1379685240585 diff = 695
Iterations = 1000000000
WithChars: start = 1379685267523 end = 1379685397604 diff = 130081
WithRegex: start = 1379685397605 end = 1379685850582 diff = 452977
You can Try this also :
public static String convertToNameCase(String s)
{
if (s != null)
{
StringBuilder b = new StringBuilder();
String[] split = s.split(" ");
for (String srt : split)
{
if (srt.length() > 0)
{
b.append(srt.substring(0, 1).toUpperCase()).append(srt.substring(1).toLowerCase()).append(" ");
}
}
return b.toString().trim();
}
return s;
}
protected String toCamelCase(String input) {
if (input == null) {
return null;
}
if (input.length() == 0) {
return "";
}
// lowercase the first character
String camelCaseStr = input.substring(0, 1).toLowerCase();
if (input.length() > 1) {
boolean isStartOfWord = false;
for (int i = 1; i < input.length(); i++) {
char currChar = input.charAt(i);
if (currChar == '_') {
// new word. ignore underscore
isStartOfWord = true;
} else if (Character.isUpperCase(currChar)) {
// capital letter. if start of word, keep it
if (isStartOfWord) {
camelCaseStr += currChar;
} else {
camelCaseStr += Character.toLowerCase(currChar);
}
isStartOfWord = false;
} else {
camelCaseStr += currChar;
isStartOfWord = false;
}
}
}
return camelCaseStr;
}
public String CamelCase(String str)
{
String CamelCase="";
String parts[] = str.split("_");
for(String part:parts)
{
String as=part.toLowerCase();
int a=as.length();
CamelCase = CamelCase + as.substring(0, 1).toUpperCase()+ as.substring(1,a);
}
return CamelCase;
}
This is the Simplest Program to convert into CamelCase.
hope it Will Help You..
public static String toCamelCase(String value) {
value = value.replace("_", " ");
String[] parts = value.split(" ");
int i = 0;
String camelCaseString = "";
for (String part : parts) {
if (part != null && !part.isEmpty()) {
if (i == 0) {
camelCaseString = part.toLowerCase();
} else if (i > 0 && part.length() > 1) {
String oldFirstChar = part.substring(0, 1);
camelCaseString = camelCaseString + part.replaceFirst(oldFirstChar, oldFirstChar.toUpperCase());
} else {
camelCaseString = camelCaseString + part + " ";
}
i++;
}
}
return camelCaseString;
}
public static void main(String[] args) {
String string = "HI_tHiS_is_SomE Statement";
System.out.println(toCamelCase(string));
}
It will convert Enum Constant into Camel Case. It would be helpful for anyone who is looking for such funtionality.
public enum TRANSLATE_LANGUAGES {
ARABIC("ar"), BULGARIAN("bg"), CATALAN("ca"), CHINESE_SIMPLIFIED("zh-CN"), CHINESE_TRADITIONAL("zh-TW"), CZECH("cs"), DANISH("da"), DUTCH("nl"), ENGLISH("en"), ESTONIAN("et"), FINNISH("fi"), FRENCH(
"fr"), GERMAN("de"), GREEK("el"), HAITIAN_CREOLE("ht"), HEBREW("he"), HINDI("hi"), HMONG_DAW("mww"), HUNGARIAN("hu"), INDONESIAN("id"), ITALIAN("it"), JAPANESE("ja"), KOREAN("ko"), LATVIAN(
"lv"), LITHUANIAN("lt"), MALAY("ms"), NORWEGIAN("no"), PERSIAN("fa"), POLISH("pl"), PORTUGUESE("pt"), ROMANIAN("ro"), RUSSIAN("ru"), SLOVAK("sk"), SLOVENIAN("sl"), SPANISH("es"), SWEDISH(
"sv"), THAI("th"), TURKISH("tr"), UKRAINIAN("uk"), URDU("ur"), VIETNAMESE("vi");
private String code;
TRANSLATE_LANGUAGES(String language) {
this.code = language;
}
public String langCode() {
return this.code;
}
public String toCamelCase(TRANSLATE_LANGUAGES lang) {
String toString = lang.toString();
if (toString.contains("_")) {
String st = toUpperLowerCase(toString.split("_"));
}
return "";
}
private String toUpperLowerCase(String[] tempString) {
StringBuilder builder = new StringBuilder();
for (String temp : tempString) {
String char1 = temp.substring(0, 1);
String restString = temp.substring(1, temp.length()).toLowerCase();
builder.append(char1).append(restString).append(" ");
}
return builder.toString();
}
}
One more solution to this may be as follows.
public static String toCamelCase(String str, String... separators) {
String separatorsRegex = "\\".concat(org.apache.commons.lang3.StringUtils.join(separators, "|\\"));
List splits = Arrays.asList(str.toLowerCase().split(separatorsRegex));
String capitalizedString = (String)splits.stream().map(WordUtils::capitalize).reduce("", String::concat);
return capitalizedString.substring(0, 1).toLowerCase() + capitalizedString.substring(1);
}
public static final String UPPER_CAMEL = "initUp";
public static final String LOWER_CAMEL = "initLow";
public String toCamel(String src, String separator, String format) {
StringBuilder builder = new StringBuilder(src.toLowerCase());
int len = builder.length();
for (int idx = builder.indexOf(separator); idx > 0 && idx < len; idx = builder.indexOf(separator, idx)) {
builder = builder.replace(idx, idx + 2, (String.valueOf(builder.charAt(idx + 1)).toUpperCase()));
}
switch (format) {
case LOWER_CAMEL:
builder.setCharAt(0, Character.toLowerCase(builder.charAt(0)));
break;
default:
builder.setCharAt(0, Character.toUpperCase(builder.charAt(0)));
break;
}
return builder.toString();
}
Invocation as
toCamel("THIS_IS_AN_EXAMPLE_STRING", "_", UPPER_CAMEL)
Execution Time: 14 ms
A simple snnipet:
public static String camelCase(String in) {
if (in == null || in.length() < 1) { return ""; } //validate in
String out = "";
for (String part : in.toLowerCase().split("_")) {
if (part.length() < 1) { //validate length
continue;
}
out += part.substring(0, 1).toUpperCase();
if (part.length() > 1) { //validate length
out += part.substring(1);
}
}
return out;
}
protected String toCamelCase(CaseFormat caseFormat, String... words){
if (words.length == 0){
throw new IllegalArgumentException("Word list is empty!");
}
String firstWord = words[0];
String [] restOfWords = Arrays.copyOfRange(words, 1, words.length);
StringBuffer buffer = new StringBuffer();
buffer.append(firstWord);
Arrays.asList(restOfWords).stream().forEach(w->buffer.append("_"+ w.toUpperCase()));
return CaseFormat.UPPER_UNDERSCORE.to(caseFormat, buffer.toString());
}
Java 8 for multiple strings:
import com.google.common.base.CaseFormat;
String camelStrings = "YOUR_UPPER, YOUR_TURN, ALT_TAB";
List<String> camelList = Arrays.asList(camelStrings.split(","));
camelList.stream().forEach(i -> System.out.println(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, i) + ", "));
Related
Input for method :
word = AbcDef
input = 3
w = AbcDef
The Following code showing the ouput :
fAbcDe
efAbcD
DefAbc
I want to return only DefAbc.
How can I do the coding for return keyword.
public static String match2(String word,int input,String w)
{
StringBuilder st = new StringBuilder();
StringBuilder st1 = new StringBuilder();
String str = "";
int count = 0;
st.append(word.charAt(i));
for(int j = 0;j < i;j++)
{
st.append(word.charAt(j));
}
if(input!=0)
{
str = st.toString();
System.out.println(str);
int input2 = input-1;
match2(str,input2,w);
}
return null;
}
Please try this one. Hope it might solve your problem using recursion-> tillValue should be->3 if you want to rotate for 3 characters
static String recurse(String word, int count, int tillValue) {
if (count == tillValue) {
return word;
}
String recurse = recurse(word, count + 1,tillValue);
word = swap(recurse);
return word;
}
private static String swap(String word) {
if (word.length() > 0) {
String c = word.substring(word.length() - 1);
String dc = c + word.substring(0, word.length() - 1);
System.out.println(dc);
return dc;
}
return "";
}
It is necessary to repeat the character, as many times as the number behind it.
They are positive integer numbers.
case #1
input: "abc3leson11"
output: "abccclesonnnnnnnnnnn"
I already finish it in the following way:
String a = "abbc2kd3ijkl40ggg2H5uu";
String s = a + "*";
String numS = "";
int cnt = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
numS = numS + ch;
cnt++;
} else {
cnt++;
try {
for (int j = 0; j < Integer.parseInt(numS); j++) {
System.out.print(s.charAt(i - cnt));
}
if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {
System.out.print(s.charAt(i));
}
} catch (Exception e) {
if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {
System.out.print(s.charAt(i));
}
}
cnt = 0;
numS = "";
}
}
But I wonder is there some better solution with less and cleaner code?
Could you take a look below? I'm using a library from StringUtils from Apache Common Utils to repeat character:
public class MicsTest {
public static void main(String[] args) {
String input = "abc3leson11";
String output = input;
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(input);
while (m.find()) {
int number = Integer.valueOf(m.group());
char repeatedChar = input.charAt(m.start()-1);
output = output.replaceFirst(m.group(), StringUtils.repeat(repeatedChar, number));
}
System.out.println(output);
}
}
In case you don't want to use StringUtils. You can use the below custom method to achieve the same effect:
public static String repeat(char c, int times) {
char[] chars = new char[times];
Arrays.fill(chars, c);
return new String(chars);
}
Using java basic string regx should make it more terse as follows:
public class He1 {
private static final Pattern pattern = Pattern.compile("[a-zA-Z]+(\\d+).*");
// match the number between or the last using regx;
public static void main(String... args) {
String s = "abc3leson11";
System.out.println(parse(s));
s = "abbc2kd3ijkl40ggg2H5uu";
System.out.println(parse(s));
}
private static String parse(String s) {
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
int num = Integer.valueOf(matcher.group(1));
char prev = s.charAt(s.indexOf(String.valueOf(num)) - 1);
// locate the char before the number;
String repeated = new String(new char[num-1]).replace('\0', prev);
// since the prev is not deleted, we have to decrement the repeating number by 1;
s = s.replaceFirst(String.valueOf(num), repeated);
matcher = pattern.matcher(s);
}
return s;
}
}
And the output should be:
abccclesonnnnnnnnnnn
abbcckdddijkllllllllllllllllllllllllllllllllllllllllggggHHHHHuu
String g(String a){
String result = "";
String[] array = a.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
//System.out.println(java.util.Arrays.toString(array));
for(int i=0; i<array.length; i++){
String part = array[i];
result += part;
if(++i == array.length){
break;
}
char charToRepeat = part.charAt(part.length() - 1);
result += repeat(charToRepeat+"", new Integer(array[i]) - 1);
}
return result;
}
// In Java 11 this could be removed and replaced with the builtin `str.repeat(amount)`
String repeat(String str, int amount){
return new String(new char[amount]).replace("\0", str);
}
Try it online.
Explanation:
The split will split the letters and numbers:
abbc2kd3ijkl40ggg2H5uu would become ["abbc", "2", "kd", "3", "ijkl", "40", "ggg", "2", "H", "5", "uu"]
We then loop over the parts and add any strings as is to the result.
We then increase i by 1 first and if we're done (after the "uu") in the array above, it will break the loop.
If not the increase of i will put us at a number. So it will repeat the last character of the part x amount of times, where x is the number we found minus 1.
Here is another solution:
String str = "abbc2kd3ijkl40ggg2H5uu";
String[] part = str.split("(?<=\\d)(?=\\D)|(?=\\d)(?<=\\D)");
String res = "";
for(int i=0; i < part.length; i++){
if(i%2 == 0){
res = res + part[i];
}else {
res = res + StringUtils.repeat(part[i-1].charAt(part[i-1].length()-1),Integer.parseInt(part[i])-1);
}
}
System.out.println(res);
Yet another solution :
public static String getCustomizedString(String input) {
ArrayList<String > letters = new ArrayList<>(Arrays.asList(input.split("(\\d)")));
letters.removeAll(Arrays.asList(""));
ArrayList<String > digits = new ArrayList<>(Arrays.asList(input.split("(\\D)")));
digits.removeAll(Arrays.asList(""));
for(int i=0; i< digits.size(); i++) {
int iteration = Integer.valueOf(digits.get(i));
String letter = letters.get(i);
char c = letter.charAt(letter.length()-1);
for (int j = 0; j<iteration -1 ; j++) {
letters.set(i,letters.get(i).concat(String.valueOf(c)));
}
}
String finalResult = "";
for (String str : letters) {
finalResult += str;
}
return finalResult;
}
The usage:
public static void main(String[] args) {
String testString1 = "abbc2kd3ijkl40ggg2H5uu";
String testString2 = "abc3leson11";
System.out.println(getCustomizedString(testString1));
System.out.println(getCustomizedString(testString2));
}
And the result:
abbcckdddijkllllllllllllllllllllllllllllllllllllllllggggHHHHHuu
abccclesonnnnnnnnnnn
String Y="part1 part2 part3",X="part1";
boolean foundMatch = false;
while(!foundMatch) {
foundMatch = Y.equals(X);
if(foundMatch) {
break;
}
else {
Y = useSplitToRemoveLastPart(Y);
if(Y.equals("")) {
break;
}
}
//implementation of useSplitToRemoveLastPart()
private static String useSplitToRemoveLastPart(String y) {
//What goes here .. It should chop the last part of the string..
return null;
}
Can anyone help ...
If you want part3 to be removed and provided that all the words are separated by space
String str ="part1 part2 part3";
String result = str.substring(0,str.lastIndexOf(" "));
If you really want to use split:
private static String useSplitToRemoveLastPart(String str) {
String[] arr = str.split(" ");
String result = "";
if (arr.length > 0) {
result = str.substring(0, str.lastIndexOf(" " + arr[arr.length-1]));
}
return result;
}
Your whole code can be optimized to:
boolean foundmatch = y.startsWith(x);
y = foundmatch? x : "";
public String removeLastSubstring(String target, String toRemove){
int idx = target.lastIndexOf(toRemove);
target = target.substring(0, idx) + target.substring(idx + toRemove.length());
return target;
}
You only need to pass it your target and the LAST substring you want to remove, example:
String s = "123 #abc# 456";
s = removeLastSubstring(s, "#abc#");
If you want to do it using split, then you can do:
String s[] = Y.split(" ");
String n = "";
for (int i = 0; i < s.length - 1; i++)
n+= s[i];
return n;
By the way, If the method you need to build is called useSplitToRemoveLastPart(String t), then I'd suggest you to use split to remove last part.
Take a look here.
The title pretty much says it all. What's the simplest/most elegant way that I can convert, in Java, a string from the format "THIS_IS_AN_EXAMPLE_STRING" to the format "ThisIsAnExampleString"? I figure there must be at least one way to do it using String.replaceAll() and a regex.
My initial thoughts are: prepend the string with an underscore (_), convert the whole string to lower case, and then use replaceAll to convert every character preceded by an underscore with its uppercase version.
Another option is using Google Guava's com.google.common.base.CaseFormat
George Hawkins left a comment with this example of usage:
CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "THIS_IS_AN_EXAMPLE_STRING");
Take a look at WordUtils in the Apache Commons lang library:
Specifically, the capitalizeFully(String str, char[] delimiters) method should do the job:
String blah = "LORD_OF_THE_RINGS";
assertEquals("LordOfTheRings", WordUtils.capitalizeFully(blah, '_').replaceAll("_", ""));
Green bar!
static String toCamelCase(String s){
String[] parts = s.split("_");
String camelCaseString = "";
for (String part : parts){
camelCaseString = camelCaseString + toProperCase(part);
}
return camelCaseString;
}
static String toProperCase(String s) {
return s.substring(0, 1).toUpperCase() +
s.substring(1).toLowerCase();
}
Note: You need to add argument validation.
With Apache Commons Lang3 lib is it very easy.
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
public String getName(String text) {
return StringUtils.remove(WordUtils.capitalizeFully(text, '_'), "_");
}
Example:
getName("SOME_CONSTANT");
Gives:
"SomeConstant"
Here is a code snippet which might help:
String input = "ABC_DEF";
StringBuilder sb = new StringBuilder();
for( String oneString : input.toLowerCase().split("_") )
{
sb.append( oneString.substring(0,1).toUpperCase() );
sb.append( oneString.substring(1) );
}
// sb now holds your desired String
Java 1.8 example using Streams
String text = "THIS_IS_SOME_TEXT";
String bactrianCamel = Stream.of(text.split("[^a-zA-Z0-9]"))
.map(v -> v.substring(0, 1).toUpperCase() + v.substring(1).toLowerCase())
.collect(Collectors.joining());
String dromedaryCamel = bactrianCamel.toLowerCase().substring(0, 1) + bactrianCamel.substring(1);
System.out.printf("%s is now %s%n", text, dromedaryCamel);
THIS_IS_SOME_TEXT is now thisIsSomeText
public static void main(String[] args) {
String start = "THIS_IS_A_TEST";
StringBuffer sb = new StringBuffer();
for (String s : start.split("_")) {
sb.append(Character.toUpperCase(s.charAt(0)));
if (s.length() > 1) {
sb.append(s.substring(1, s.length()).toLowerCase());
}
}
System.out.println(sb);
}
The Apache Commons project does now have the CaseUtils class, which has a toCamelCase method that does exactly as OP asked:
CaseUtils.toCamelCase("THIS_IS_AN_EXAMPLE_STRING", true, '_');
Sorry for mine five cents, I think in java too many words))
I just wondering. Why is the regexp engine in java not so familiar with lambdas as in JS((
Anyway. With java 8+ construction appears in my mind:
Arrays.stream("THIS_IS_AN_EXAMPLE_STRING".split("_"))
.collect(StringBuilder::new,
(result, w) -> result
.append(w.substring(0, 1).toUpperCase())
.append(w.substring(1).toLowerCase()),
StringBuilder::append)
.toString())
If you care about memory consumption, the below code care about it:
"THIS_IS_AN_EXAMPLE_STRING".chars().collect(StringBuilder::new,
(result, c) -> {
// Detect place for deal with
if (result.length() > 0 && result.charAt(result.length() - 1) == '_') {
result.setCharAt(result.length() - 1,
Character.toUpperCase((char) c));
} else if (result.length() > 0) {
result.append(Character.toLowerCase((char) c));
} else {
result.append(Character.toUpperCase((char) c));
}
}, StringBuilder::append).toString()
You can use org.modeshape.common.text.Inflector.
Specifically:
String camelCase(String lowerCaseAndUnderscoredWord,
boolean uppercaseFirstLetter, char... delimiterChars)
By default, this method converts strings to UpperCamelCase.
Maven artifact is: org.modeshape:modeshape-common:2.3.0.Final
on JBoss repository: https://repository.jboss.org/nexus/content/repositories/releases
Here's the JAR file: https://repository.jboss.org/nexus/content/repositories/releases/org/modeshape/modeshape-common/2.3.0.Final/modeshape-common-2.3.0.Final.jar
Not sure, but I think I can use less memory and get dependable performance by doing it char-by-char. I was doing something similar, but in loops in background threads, so I am trying this for now. I've had some experience with String.split being more expensive then expected. And I am working on Android and expect GC hiccups to be more of an issue then cpu use.
public static String toCamelCase(String value) {
StringBuilder sb = new StringBuilder();
final char delimChar = '_';
boolean lower = false;
for (int charInd = 0; charInd < value.length(); ++charInd) {
final char valueChar = value.charAt(charInd);
if (valueChar == delimChar) {
lower = false;
} else if (lower) {
sb.append(Character.toLowerCase(valueChar));
} else {
sb.append(Character.toUpperCase(valueChar));
lower = true;
}
}
return sb.toString();
}
A hint that String.split is expensive is that its input is a regex (not a char like String.indexOf) and it returns an array (instead of say an iterator because the loop only uses one things at a time). Plus cases like "AB_AB_AB_AB_AB_AB..." break the efficiency of any bulk copy, and for long strings use an order of magnitude more memory then the input string.
Whereas looping through chars has no canonical case. So to me the overhead of an unneeded regex and array seems generally less preferable (then giving up possible bulk copy efficiency). Interested to hear opinions / corrections, thanks.
public String withChars(String inputa) {
String input = inputa.toLowerCase();
StringBuilder sb = new StringBuilder();
final char delim = '_';
char value;
boolean capitalize = false;
for (int i=0; i<input.length(); ++i) {
value = input.charAt(i);
if (value == delim) {
capitalize = true;
}
else if (capitalize) {
sb.append(Character.toUpperCase(value));
capitalize = false;
}
else {
sb.append(value);
}
}
return sb.toString();
}
public String withRegex(String inputa) {
String input = inputa.toLowerCase();
String[] parts = input.split("_");
StringBuilder sb = new StringBuilder();
sb.append(parts[0]);
for (int i=1; i<parts.length; ++i) {
sb.append(parts[i].substring(0,1).toUpperCase());
sb.append(parts[i].substring(1));
}
return sb.toString();
}
Times: in milli seconds.
Iterations = 1000
WithChars: start = 1379685214671 end = 1379685214683 diff = 12
WithRegex: start = 1379685214683 end = 1379685214712 diff = 29
Iterations = 1000
WithChars: start = 1379685217033 end = 1379685217045 diff = 12
WithRegex: start = 1379685217045 end = 1379685217077 diff = 32
Iterations = 1000
WithChars: start = 1379685218643 end = 1379685218654 diff = 11
WithRegex: start = 1379685218655 end = 1379685218684 diff = 29
Iterations = 1000000
WithChars: start = 1379685232767 end = 1379685232968 diff = 201
WithRegex: start = 1379685232968 end = 1379685233649 diff = 681
Iterations = 1000000
WithChars: start = 1379685237220 end = 1379685237419 diff = 199
WithRegex: start = 1379685237419 end = 1379685238088 diff = 669
Iterations = 1000000
WithChars: start = 1379685239690 end = 1379685239889 diff = 199
WithRegex: start = 1379685239890 end = 1379685240585 diff = 695
Iterations = 1000000000
WithChars: start = 1379685267523 end = 1379685397604 diff = 130081
WithRegex: start = 1379685397605 end = 1379685850582 diff = 452977
You can Try this also :
public static String convertToNameCase(String s)
{
if (s != null)
{
StringBuilder b = new StringBuilder();
String[] split = s.split(" ");
for (String srt : split)
{
if (srt.length() > 0)
{
b.append(srt.substring(0, 1).toUpperCase()).append(srt.substring(1).toLowerCase()).append(" ");
}
}
return b.toString().trim();
}
return s;
}
protected String toCamelCase(String input) {
if (input == null) {
return null;
}
if (input.length() == 0) {
return "";
}
// lowercase the first character
String camelCaseStr = input.substring(0, 1).toLowerCase();
if (input.length() > 1) {
boolean isStartOfWord = false;
for (int i = 1; i < input.length(); i++) {
char currChar = input.charAt(i);
if (currChar == '_') {
// new word. ignore underscore
isStartOfWord = true;
} else if (Character.isUpperCase(currChar)) {
// capital letter. if start of word, keep it
if (isStartOfWord) {
camelCaseStr += currChar;
} else {
camelCaseStr += Character.toLowerCase(currChar);
}
isStartOfWord = false;
} else {
camelCaseStr += currChar;
isStartOfWord = false;
}
}
}
return camelCaseStr;
}
public String CamelCase(String str)
{
String CamelCase="";
String parts[] = str.split("_");
for(String part:parts)
{
String as=part.toLowerCase();
int a=as.length();
CamelCase = CamelCase + as.substring(0, 1).toUpperCase()+ as.substring(1,a);
}
return CamelCase;
}
This is the Simplest Program to convert into CamelCase.
hope it Will Help You..
public static String toCamelCase(String value) {
value = value.replace("_", " ");
String[] parts = value.split(" ");
int i = 0;
String camelCaseString = "";
for (String part : parts) {
if (part != null && !part.isEmpty()) {
if (i == 0) {
camelCaseString = part.toLowerCase();
} else if (i > 0 && part.length() > 1) {
String oldFirstChar = part.substring(0, 1);
camelCaseString = camelCaseString + part.replaceFirst(oldFirstChar, oldFirstChar.toUpperCase());
} else {
camelCaseString = camelCaseString + part + " ";
}
i++;
}
}
return camelCaseString;
}
public static void main(String[] args) {
String string = "HI_tHiS_is_SomE Statement";
System.out.println(toCamelCase(string));
}
It will convert Enum Constant into Camel Case. It would be helpful for anyone who is looking for such funtionality.
public enum TRANSLATE_LANGUAGES {
ARABIC("ar"), BULGARIAN("bg"), CATALAN("ca"), CHINESE_SIMPLIFIED("zh-CN"), CHINESE_TRADITIONAL("zh-TW"), CZECH("cs"), DANISH("da"), DUTCH("nl"), ENGLISH("en"), ESTONIAN("et"), FINNISH("fi"), FRENCH(
"fr"), GERMAN("de"), GREEK("el"), HAITIAN_CREOLE("ht"), HEBREW("he"), HINDI("hi"), HMONG_DAW("mww"), HUNGARIAN("hu"), INDONESIAN("id"), ITALIAN("it"), JAPANESE("ja"), KOREAN("ko"), LATVIAN(
"lv"), LITHUANIAN("lt"), MALAY("ms"), NORWEGIAN("no"), PERSIAN("fa"), POLISH("pl"), PORTUGUESE("pt"), ROMANIAN("ro"), RUSSIAN("ru"), SLOVAK("sk"), SLOVENIAN("sl"), SPANISH("es"), SWEDISH(
"sv"), THAI("th"), TURKISH("tr"), UKRAINIAN("uk"), URDU("ur"), VIETNAMESE("vi");
private String code;
TRANSLATE_LANGUAGES(String language) {
this.code = language;
}
public String langCode() {
return this.code;
}
public String toCamelCase(TRANSLATE_LANGUAGES lang) {
String toString = lang.toString();
if (toString.contains("_")) {
String st = toUpperLowerCase(toString.split("_"));
}
return "";
}
private String toUpperLowerCase(String[] tempString) {
StringBuilder builder = new StringBuilder();
for (String temp : tempString) {
String char1 = temp.substring(0, 1);
String restString = temp.substring(1, temp.length()).toLowerCase();
builder.append(char1).append(restString).append(" ");
}
return builder.toString();
}
}
One more solution to this may be as follows.
public static String toCamelCase(String str, String... separators) {
String separatorsRegex = "\\".concat(org.apache.commons.lang3.StringUtils.join(separators, "|\\"));
List splits = Arrays.asList(str.toLowerCase().split(separatorsRegex));
String capitalizedString = (String)splits.stream().map(WordUtils::capitalize).reduce("", String::concat);
return capitalizedString.substring(0, 1).toLowerCase() + capitalizedString.substring(1);
}
public static final String UPPER_CAMEL = "initUp";
public static final String LOWER_CAMEL = "initLow";
public String toCamel(String src, String separator, String format) {
StringBuilder builder = new StringBuilder(src.toLowerCase());
int len = builder.length();
for (int idx = builder.indexOf(separator); idx > 0 && idx < len; idx = builder.indexOf(separator, idx)) {
builder = builder.replace(idx, idx + 2, (String.valueOf(builder.charAt(idx + 1)).toUpperCase()));
}
switch (format) {
case LOWER_CAMEL:
builder.setCharAt(0, Character.toLowerCase(builder.charAt(0)));
break;
default:
builder.setCharAt(0, Character.toUpperCase(builder.charAt(0)));
break;
}
return builder.toString();
}
Invocation as
toCamel("THIS_IS_AN_EXAMPLE_STRING", "_", UPPER_CAMEL)
Execution Time: 14 ms
A simple snnipet:
public static String camelCase(String in) {
if (in == null || in.length() < 1) { return ""; } //validate in
String out = "";
for (String part : in.toLowerCase().split("_")) {
if (part.length() < 1) { //validate length
continue;
}
out += part.substring(0, 1).toUpperCase();
if (part.length() > 1) { //validate length
out += part.substring(1);
}
}
return out;
}
protected String toCamelCase(CaseFormat caseFormat, String... words){
if (words.length == 0){
throw new IllegalArgumentException("Word list is empty!");
}
String firstWord = words[0];
String [] restOfWords = Arrays.copyOfRange(words, 1, words.length);
StringBuffer buffer = new StringBuffer();
buffer.append(firstWord);
Arrays.asList(restOfWords).stream().forEach(w->buffer.append("_"+ w.toUpperCase()));
return CaseFormat.UPPER_UNDERSCORE.to(caseFormat, buffer.toString());
}
Java 8 for multiple strings:
import com.google.common.base.CaseFormat;
String camelStrings = "YOUR_UPPER, YOUR_TURN, ALT_TAB";
List<String> camelList = Arrays.asList(camelStrings.split(","));
camelList.stream().forEach(i -> System.out.println(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, i) + ", "));
Are there any built in methods available to convert a string into Title Case format?
Apache Commons StringUtils.capitalize() or Commons Text WordUtils.capitalize()
e.g: WordUtils.capitalize("i am FINE") = "I Am FINE" from WordUtils doc
There are no capitalize() or titleCase() methods in Java's String class. You have two choices:
using commons lang string utils.
StringUtils.capitalize(null) = null
StringUtils.capitalize("") = ""
StringUtils.capitalize("cat") = "Cat"
StringUtils.capitalize("cAt") = "CAt"
StringUtils.capitalize("'cat'") = "'cat'"
write (yet another) static helper method toTitleCase()
Sample implementation
public static String toTitleCase(String input) {
StringBuilder titleCase = new StringBuilder(input.length());
boolean nextTitleCase = true;
for (char c : input.toCharArray()) {
if (Character.isSpaceChar(c)) {
nextTitleCase = true;
} else if (nextTitleCase) {
c = Character.toTitleCase(c);
nextTitleCase = false;
}
titleCase.append(c);
}
return titleCase.toString();
}
Testcase
System.out.println(toTitleCase("string"));
System.out.println(toTitleCase("another string"));
System.out.println(toTitleCase("YET ANOTHER STRING"));
outputs:
String
Another String
YET ANOTHER STRING
If I may submit my take on the solution...
The following method is based on the one that dfa posted. It makes the following major change (which is suited to the solution I needed at the time): it forces all characters in the input string into lower case unless it is immediately preceded by an "actionable delimiter" in which case the character is coerced into upper case.
A major limitation of my routine is that it makes the assumption that "title case" is uniformly defined for all locales and is represented by the same case conventions I have used and so it is less useful than dfa's code in that respect.
public static String toDisplayCase(String s) {
final String ACTIONABLE_DELIMITERS = " '-/"; // these cause the character following
// to be capitalized
StringBuilder sb = new StringBuilder();
boolean capNext = true;
for (char c : s.toCharArray()) {
c = (capNext)
? Character.toUpperCase(c)
: Character.toLowerCase(c);
sb.append(c);
capNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0); // explicit cast not needed
}
return sb.toString();
}
TEST VALUES
a string
maRTin o'maLLEY
john wilkes-booth
YET ANOTHER STRING
OUTPUTS
A String
Martin O'Malley
John Wilkes-Booth
Yet Another String
Use WordUtils.capitalizeFully() from Apache Commons.
WordUtils.capitalizeFully(null) = null
WordUtils.capitalizeFully("") = ""
WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
You can use apache commons langs like this :
WordUtils.capitalizeFully("this is a text to be capitalize")
you can find the java doc here :
WordUtils.capitalizeFully java doc
and if you want to remove the spaces in between the worlds you can use :
StringUtils.remove(WordUtils.capitalizeFully("this is a text to be capitalize")," ")
you can find the java doc for String
StringUtils.remove java doc
i hope this help.
If you want the correct answer according to the latest Unicode standard, you should use icu4j.
UCharacter.toTitleCase(Locale.US, "hello world", null, 0);
Note that this is locale sensitive.
Api Documentation
Implementation
Here's another take based on #dfa's and #scottb's answers that handles any non-letter/digit characters:
public final class TitleCase {
public static String toTitleCase(String input) {
StringBuilder titleCase = new StringBuilder(input.length());
boolean nextTitleCase = true;
for (char c : input.toLowerCase().toCharArray()) {
if (!Character.isLetterOrDigit(c)) {
nextTitleCase = true;
} else if (nextTitleCase) {
c = Character.toTitleCase(c);
nextTitleCase = false;
}
titleCase.append(c);
}
return titleCase.toString();
}
}
Given input:
MARY ÄNN O’CONNEŽ-ŠUSLIK
the output is
Mary Änn O’Connež-Šuslik
This is something I wrote to convert snake_case to lowerCamelCase but could easily be adjusted based on the requirements
private String convertToLowerCamel(String startingText)
{
String[] parts = startingText.split("_");
return parts[0].toLowerCase() + Arrays.stream(parts)
.skip(1)
.map(part -> part.substring(0, 1).toUpperCase() + part.substring(1).toLowerCase())
.collect(Collectors.joining());
}
Using Spring's StringUtils:
org.springframework.util.StringUtils.capitalize(someText);
If you're already using Spring anyway, this avoids bringing in another framework.
Use this method to convert a string to title case :
static String toTitleCase(String word) {
return Stream.of(word.split(" "))
.map(w -> w.toUpperCase().charAt(0)+ w.toLowerCase().substring(1))
.reduce((s, s2) -> s + " " + s2).orElse("");
}
I know this is older one, but doesn't carry the simple answer, I needed this method for my coding so I added here, simple to use.
public static String toTitleCase(String input) {
input = input.toLowerCase();
char c = input.charAt(0);
String s = new String("" + c);
String f = s.toUpperCase();
return f + input.substring(1);
}
you can very well use
org.apache.commons.lang.WordUtils
or
CaseFormat
from Google's API.
I had this problem and i searched for it
then i made my own method using some java keywords
just need to pass String variable as parameter and get output as proper titled String.
public class Main
{
public static void main (String[]args)
{
String st = "pARVeEN sISHOsIYA";
String mainn = getTitleCase (st);
System.out.println (mainn);
}
public static String getTitleCase(String input)
{
StringBuilder titleCase = new StringBuilder (input.length());
boolean hadSpace = false;
for (char c:input.toCharArray ()){
if(Character.isSpaceChar(c)){
hadSpace = true;
titleCase.append (c);
continue;
}
if(hadSpace){
hadSpace = false;
c = Character.toUpperCase(c);
titleCase.append (c);
}else{
c = Character.toLowerCase(c);
titleCase.append (c);
}
}
String temp=titleCase.toString ();
StringBuilder titleCase1 = new StringBuilder (temp.length ());
int num=1;
for (char c:temp.toCharArray ())
{ if(num==1)
c = Character.toUpperCase(c);
titleCase1.append (c);
num=0;
}
return titleCase1.toString ();
}
}
It seems none of the answers format it in the actual title case: "How to Land Your Dream Job", "To Kill a Mockingbird", etc. so I've made my own method. Works best for English languages texts.
private final static Set<Character> TITLE_CASE_DELIMITERS = new HashSet<>();
static {
TITLE_CASE_DELIMITERS.add(' ');
TITLE_CASE_DELIMITERS.add('.');
TITLE_CASE_DELIMITERS.add(',');
TITLE_CASE_DELIMITERS.add(';');
TITLE_CASE_DELIMITERS.add('/');
TITLE_CASE_DELIMITERS.add('-');
TITLE_CASE_DELIMITERS.add('(');
TITLE_CASE_DELIMITERS.add(')');
}
private final static Set<String> TITLE_SMALLCASED_WORDS = new HashSet<>();
static {
TITLE_SMALLCASED_WORDS.add("a");
TITLE_SMALLCASED_WORDS.add("an");
TITLE_SMALLCASED_WORDS.add("the");
TITLE_SMALLCASED_WORDS.add("for");
TITLE_SMALLCASED_WORDS.add("in");
TITLE_SMALLCASED_WORDS.add("on");
TITLE_SMALLCASED_WORDS.add("of");
TITLE_SMALLCASED_WORDS.add("and");
TITLE_SMALLCASED_WORDS.add("but");
TITLE_SMALLCASED_WORDS.add("or");
TITLE_SMALLCASED_WORDS.add("nor");
TITLE_SMALLCASED_WORDS.add("to");
}
public static String toCapitalizedWord(String oneWord) {
if (oneWord.length() < 1) {
return oneWord.toUpperCase();
}
return "" + Character.toTitleCase(oneWord.charAt(0)) + oneWord.substring(1).toLowerCase();
}
public static String toTitledWord(String oneWord) {
if (TITLE_SMALLCASED_WORDS.contains(oneWord.toLowerCase())) {
return oneWord.toLowerCase();
}
return toCapitalizedWord(oneWord);
}
public static String toTitleCase(String str) {
StringBuilder result = new StringBuilder();
StringBuilder oneWord = new StringBuilder();
char previousDelimiter = 'x';
/* on start, always move to upper case */
for (char c : str.toCharArray()) {
if (TITLE_CASE_DELIMITERS.contains(c)) {
if (previousDelimiter == '-' || previousDelimiter == 'x') {
result.append(toCapitalizedWord(oneWord.toString()));
} else {
result.append(toTitledWord(oneWord.toString()));
}
oneWord.setLength(0);
result.append(c);
previousDelimiter = c;
} else {
oneWord.append(c);
}
}
if (previousDelimiter == '-' || previousDelimiter == 'x') {
result.append(toCapitalizedWord(oneWord.toString()));
} else {
result.append(toTitledWord(oneWord.toString()));
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(toTitleCase("one year in paris"));
System.out.println(toTitleCase("How to Land Your Dream Job"));
}
This is the simplest solution
static void title(String a,String b){
String ra = Character.toString(Character.toUpperCase(a.charAt(0)));
String rb = Character.toString(Character.toUpperCase(b.charAt(0)));
for(int i=1;i<a.length();i++){
ra+=a.charAt(i);
}
for(int i=1;i<b.length();i++){
rb+=b.charAt(i);
}
System.out.println(ra+" "+rb);
I recently ran into this problem too and unfortunately had many occurences of names beginning with Mc and Mac, I ended up using a version of scottb's code which I changed to handle these prefixes so it's here in case anyone wants to use it.
There are still edge cases which this misses but the worst thing that can happen is that a letter will be lower case when it should be capitalized.
/**
* Get a nicely formatted representation of the name.
* Don't send this the whole name at once, instead send it the components.<br>
* For example: andrew macnamara would be returned as:<br>
* Andrew Macnamara if processed as a single string<br>
* Andrew MacNamara if processed as 2 strings.
* #param name
* #return correctly formatted name
*/
public static String getNameTitleCase (String name) {
final String ACTIONABLE_DELIMITERS = " '-/";
StringBuilder sb = new StringBuilder();
if (name !=null && !name.isEmpty()){
boolean capitaliseNext = true;
for (char c : name.toCharArray()) {
c = (capitaliseNext)?Character.toUpperCase(c):Character.toLowerCase(c);
sb.append(c);
capitaliseNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0);
}
name = sb.toString();
if (name.startsWith("Mc") && name.length() > 2 ) {
char c = name.charAt(2);
if (ACTIONABLE_DELIMITERS.indexOf((int) c) < 0) {
sb = new StringBuilder();
sb.append (name.substring(0,2));
sb.append (name.substring(2,3).toUpperCase());
sb.append (name.substring(3));
name=sb.toString();
}
} else if (name.startsWith("Mac") && name.length() > 3) {
char c = name.charAt(3);
if (ACTIONABLE_DELIMITERS.indexOf((int) c) < 0) {
sb = new StringBuilder();
sb.append (name.substring(0,3));
sb.append (name.substring(3,4).toUpperCase());
sb.append (name.substring(4));
name=sb.toString();
}
}
}
return name;
}
Conversion to Proper Title Case :
String s= "ThiS iS SomE Text";
String[] arr = s.split(" ");
s = "";
for (String s1 : arr) {
s += WordUtils.capitalize(s1.toLowerCase()) + " ";
}
s = s.substring(0, s.length() - 1);
Result : "This Is Some Text"
This converter transform any string containing camel case, white-spaces, digits and other characters to sanitized title case.
/**
* Convert a string to title case in java (with tests).
*
* #author Sudipto Chandra
*/
public abstract class TitleCase {
/**
* Returns the character type. <br>
* <br>
* Digit = 2 <br>
* Lower case alphabet = 0 <br>
* Uppercase case alphabet = 1 <br>
* All else = -1.
*
* #param ch
* #return
*/
private static int getCharType(char ch) {
if (Character.isLowerCase(ch)) {
return 0;
} else if (Character.isUpperCase(ch)) {
return 1;
} else if (Character.isDigit(ch)) {
return 2;
}
return -1;
}
/**
* Converts any given string in camel or snake case to title case.
* <br>
* It uses the method getCharType and ignore any character that falls in
* negative character type category. It separates two alphabets of not-equal
* cases with a space. It accepts numbers and append it to the currently
* running group, and puts a space at the end.
* <br>
* If the result is empty after the operations, original string is returned.
*
* #param text the text to be converted.
* #return a title cased string
*/
public static String titleCase(String text) {
if (text == null || text.length() == 0) {
return text;
}
char[] str = text.toCharArray();
StringBuilder sb = new StringBuilder();
boolean capRepeated = false;
for (int i = 0, prev = -1, next; i < str.length; ++i, prev = next) {
next = getCharType(str[i]);
// trace consecutive capital cases
if (prev == 1 && next == 1) {
capRepeated = true;
} else if (next != 0) {
capRepeated = false;
}
// next is ignorable
if (next == -1) {
// System.out.printf("case 0, %d %d %s\n", prev, next, sb.toString());
continue; // does not append anything
}
// prev and next are of same type
if (prev == next) {
sb.append(str[i]);
// System.out.printf("case 1, %d %d %s\n", prev, next, sb.toString());
continue;
}
// next is not an alphabet
if (next == 2) {
sb.append(str[i]);
// System.out.printf("case 2, %d %d %s\n", prev, next, sb.toString());
continue;
}
// next is an alphabet, prev was not +
// next is uppercase and prev was lowercase
if (prev == -1 || prev == 2 || prev == 0) {
if (sb.length() != 0) {
sb.append(' ');
}
sb.append(Character.toUpperCase(str[i]));
// System.out.printf("case 3, %d %d %s\n", prev, next, sb.toString());
continue;
}
// next is lowercase and prev was uppercase
if (prev == 1) {
if (capRepeated) {
sb.insert(sb.length() - 1, ' ');
capRepeated = false;
}
sb.append(str[i]);
// System.out.printf("case 4, %d %d %s\n", prev, next, sb.toString());
}
}
String output = sb.toString().trim();
output = (output.length() == 0) ? text : output;
//return output;
// Capitalize all words (Optional)
String[] result = output.split(" ");
for (int i = 0; i < result.length; ++i) {
result[i] = result[i].charAt(0) + result[i].substring(1).toLowerCase();
}
output = String.join(" ", result);
return output;
}
/**
* Test method for the titleCase() function.
*/
public static void testTitleCase() {
System.out.println("--------------- Title Case Tests --------------------");
String[][] samples = {
{null, null},
{"", ""},
{"a", "A"},
{"aa", "Aa"},
{"aaa", "Aaa"},
{"aC", "A C"},
{"AC", "Ac"},
{"aCa", "A Ca"},
{"ACa", "A Ca"},
{"aCamel", "A Camel"},
{"anCamel", "An Camel"},
{"CamelCase", "Camel Case"},
{"camelCase", "Camel Case"},
{"snake_case", "Snake Case"},
{"toCamelCaseString", "To Camel Case String"},
{"toCAMELCase", "To Camel Case"},
{"_under_the_scoreCamelWith_", "Under The Score Camel With"},
{"ABDTest", "Abd Test"},
{"title123Case", "Title123 Case"},
{"expect11", "Expect11"},
{"all0verMe3", "All0 Ver Me3"},
{"___", "___"},
{"__a__", "A"},
{"_A_b_c____aa", "A B C Aa"},
{"_get$It132done", "Get It132 Done"},
{"_122_", "122"},
{"_no112", "No112"},
{"Case-13title", "Case13 Title"},
{"-no-allow-", "No Allow"},
{"_paren-_-allow--not!", "Paren Allow Not"},
{"Other.Allow.--False?", "Other Allow False"},
{"$39$ldl%LK3$lk_389$klnsl-32489 3 42034 ", "39 Ldl Lk3 Lk389 Klnsl32489342034"},
{"tHis will BE MY EXAMple", "T His Will Be My Exa Mple"},
{"stripEvery.damn-paren- -_now", "Strip Every Damn Paren Now"},
{"getMe", "Get Me"},
{"whatSthePoint", "What Sthe Point"},
{"n0pe_aLoud", "N0 Pe A Loud"},
{"canHave SpacesThere", "Can Have Spaces There"},
{" why_underScore exists ", "Why Under Score Exists"},
{"small-to-be-seen", "Small To Be Seen"},
{"toCAMELCase", "To Camel Case"},
{"_under_the_scoreCamelWith_", "Under The Score Camel With"},
{"last one onTheList", "Last One On The List"}
};
int pass = 0;
for (String[] inp : samples) {
String out = titleCase(inp[0]);
//String out = WordUtils.capitalizeFully(inp[0]);
System.out.printf("TEST '%s'\nWANTS '%s'\nFOUND '%s'\n", inp[0], inp[1], out);
boolean passed = (out == null ? inp[1] == null : out.equals(inp[1]));
pass += passed ? 1 : 0;
System.out.println(passed ? "-- PASS --" : "!! FAIL !!");
System.out.println();
}
System.out.printf("\n%d Passed, %d Failed.\n", pass, samples.length - pass);
}
public static void main(String[] args) {
// run tests
testTitleCase();
}
}
Here are some inputs:
aCamel
TitleCase
snake_case
fromCamelCASEString
ABCTest
expect11
_paren-_-allow--not!
why_underScore exists
last one onTheList
And my outputs:
A Camel
Title Case
Snake Case
From Camel Case String
Abc Test
Expect11
Paren Allow Not
Why Under Score Exists
Last One On The List
Without dependency -
public static String capitalizeFirstLetter(String s) {
if(s.trim().length()>0){
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
return s;
}
public static String createTitleCase(String s) {
if(s.trim().length()>0){
final StringBuilder sb = new StringBuilder();
String[] strArr = s.split("\\s*");
for(String s1 : strArr) {
sb.append(capitalizeFirstLetter(s1));
}
s = sb.toString();
sb.setLength(0);
}
return s;
}
This should work:
String str="i like pancakes";
String arr[]=str.split(" ");
String strNew="";
for(String str1:arr)
{
Character oldchar=str1.charAt(0);
Character newchar=Character.toUpperCase(str1.charAt(0));
strNew=strNew+str1.replace(oldchar,newchar)+" ";
}
System.out.println(strNew);
The simplest way of converting any string into a title case, is to use googles package org.apache.commons.lang.WordUtils
System.out.println(WordUtils.capitalizeFully("tHis will BE MY EXAMple"));
Will result this
This Will Be My Example
I'm not sure why its named "capitalizeFully", where in fact the function is not doing a full capital result, but anyways, thats the tool that we need.
Sorry I am a beginner so my coding habit sucks!
public class TitleCase {
String title(String sent)
{
sent =sent.trim();
sent = sent.toLowerCase();
String[] str1=new String[sent.length()];
for(int k=0;k<=str1.length-1;k++){
str1[k]=sent.charAt(k)+"";
}
for(int i=0;i<=sent.length()-1;i++){
if(i==0){
String s= sent.charAt(i)+"";
str1[i]=s.toUpperCase();
}
if(str1[i].equals(" ")){
String s= sent.charAt(i+1)+"";
str1[i+1]=s.toUpperCase();
}
System.out.print(str1[i]);
}
return "";
}
public static void main(String[] args) {
TitleCase a = new TitleCase();
System.out.println(a.title(" enter your Statement!"));
}
}