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;
}
\$\endgroup\$
1
  • \$\begingroup\$ What if both the strings are of different length? \$\endgroup\$
    – Ankit Soni
    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]);
    }
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ And some length check for safety \$\endgroup\$
    – Teddy
    Jul 22, 2018 at 9:02
  • \$\begingroup\$ Updated with min(apple.length(),orange.length()) \$\endgroup\$
    – rbishnoi
    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;
     }
\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.