2
\$\begingroup\$

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;
}
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jul 20, 2018 at 23:57
\$\endgroup\$
1
  • \$\begingroup\$ What if both the strings are of different length? \$\endgroup\$ Commented Jul 21, 2018 at 7:10

2 Answers 2

3
\$\begingroup\$

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]);
 }
}
answered Jul 21, 2018 at 8:18
\$\endgroup\$
2
  • 1
    \$\begingroup\$ And some length check for safety \$\endgroup\$ Commented Jul 22, 2018 at 9:02
  • \$\begingroup\$ Updated with min(apple.length(),orange.length()) \$\endgroup\$ Commented Aug 4, 2018 at 16:12
0
\$\begingroup\$

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;
 }
answered Jul 21, 2018 at 12:24
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.