Change lowercase and uppercase of characters in java

1.7k views Asked by At

If I want to create a dictionary where the user can create a custom alphabet (that still uses unicode) Is there a way to change lowercase and uppercase mapping of the characters?

Let's say I want the lowercase of 'I' to be 'ı' instead of 'i' or upperCase of 'b' to be 'P' instead of 'B' so that System.out.println("PAI".toLowerCase()); would write baı to the console.

I suppose I can create a method toLowerCase(String s) that first replaces "P" with "b"s then converts to lowercase but wouldn't that be slower when searching through a dictionary of hundreds of thousands of words?

4

There are 4 answers

2
Hummeling Engineering BV On BEST ANSWER

This should do the trick:

import java.util.HashMap;
import java.util.Map;

class MyString {

    String string;
    static final Map<Character, Character> toLowerCaseMap, toUpperCaseMap;

    static {
        toLowerCaseMap = new HashMap<>();
        toLowerCaseMap.put('I', '|');

        toUpperCaseMap = new HashMap<>();
        toUpperCaseMap.put('b', 'P');
    }

    MyString(String string) {

        this.string = string;
    }

    String toLowerCase() {

        char[] chars = string.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            chars[i] = toLowerCaseMap.containsKey(c) ? toLowerCaseMap.get(c) : Character.toLowerCase(c);
        }

        return new String(chars);
    }

    String toUpperCase() {

        char[] chars = string.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            chars[i] = toUpperCaseMap.containsKey(c) ? toUpperCaseMap.get(c) : Character.toUpperCase(c);
        }

        return new String(chars);
    }
}
2
Paizo On

The toLowerCase(String s) uses the locale to decide how to convert the characters, you should have to define your own locale and then, for example, load it as the default locale via Locale.setDefault(Locale) before executing the toLowerCase(String s)

11
Toby Caulk On

No, it would not be slower because you are simply traversing through the array and not modifying the position of any object which would result in O(n). Performance wouldn't be affected, and any system should be able to handle a single conversion and then toLowerCase call easily.

You could also override the toLowerCase(String s) function to accommodate your needs. Even simpler!

3
jorge polanco On

Check this Answer you cannot inherits from String Class because its final, but you could create your class with your toLowerCase Method, I suggest you called diferents for maintenance.

And for the dictionary of hundreds of thousands of words.... Maybe you use a Map or HashMap with the key will be the string enter by the user and in the object you maybe save automatically the value in lowerCase, it depends of what you need.

But for get better performance I could recommend save the value in Database

Regards.