I want to take the capitalization of one string and apply it to another.
For example: take Apple
and orange
and turn that into Orange
.
This is the solution I implemented. Is there a more efficient way of doing this?
public static String applyCapitalization(String to, String from) {
int[] capArray = toCapitalizationArray(to);
char[] charCap = from.toCharArray();
for (int i = 0; i < capArray.length; i++) {
if (capArray[i] == 1) {
charCap[i] = Character.toUpperCase(charCap[i]);
} else {
charCap[i] = Character.toLowerCase(charCap[i]);
}
}
return new String(charCap);
}
private static int[] toCapitalizationArray(String to) {
int[] arr = new int[to.length()];
for (int i = 0; i < to.length(); i++) {
char c = to.toCharArray()[i];
if (Character.isUpperCase(c)) {
arr[i] = 1;
} else {
arr[i] = 0;
}
}
return arr;
}
-
\$\begingroup\$ What if both the strings are of different length? \$\endgroup\$Ankit Soni– Ankit Soni2018年07月21日 07:10:13 +00:00Commented Jul 21, 2018 at 7:10
2 Answers 2
We can do this in single traversal rather then two
for (int i = 0; i < min(apple.length(),orange.length()); i++) {
if (Character.isUpperCase(apple.toCharArray()[i]) &&
Character.isLowercase(oranger.toCharArray()[i])){
orange[i] = Character.toUppercase(oranger.toCharArray()[i]);
}elseif(Character.isLowerCase(apple.toCharArray()[i]) &&
Character.isUppercase(oranger.toCharArray()[i])){
orange[i] = Character.toLowercase(oranger.toCharArray()[i]);
}
}
For example: take Apple and orange and turn that into Orange.
I don't understand this statement
However if you want to capitalize any string, you only have to use the replace function of the String class
public static String capitalize(String word){
String capitalizedString = null;
if (word != null && word.getClass() == String.class) {
try {
capitalizedString = word.replace(String.valueOf(word.charAt(0)),
String.valueOf(word.toUpperCase().charAt(0)));
} catch (Exception exc) {
System.out.print(exc);
}
}
return capitalizedString;
}