Reputation: 77
I am trying to implement the equivalent of the keyboards "shift" key that when pressed will update the UI text to either capital letters, or for example "@" instead of 2.
I've tried the toCapital and the toLowerCase functions but they don't appear to work for symbols which is arguably the more important of the two.
Code isn't really required to help me answer this problem but here is a simple psuedo-code layout of what I want to happen
UI Element x;
UI Element five;
five.setText("5");
x.setText("x");
// Hopefully this shifting function would return
applyShift(x.getText()) == 'X' TRUE
applyShift(five.getText()) == '%' TRUE
// and if we were to apply shift again they would go back to their original values
Does a function like this exist?
Upvotes: 2
Views: 392
Reputation: 10253
I think the closest you could get is perhaps creating a different Map for each keyboard layout you want to support and manually setting the key, value pairs yourself.
This would not be a trivial task as you'd need to account for an unknown number of keyboard layouts, but if you're only planning to support a few layouts, this might work.
Here is a quick example:
import java.util.HashMap;
import java.util.Map;
enum KeyboardLayout {
// Would need to include additional supported keyboard layouts here.
QWERTY
}
class Scratch {
public static void main(String[] args) {
String input = "Hello123";
System.out.println(applyShift(input, getShiftMap(KeyboardLayout.QWERTY)));
}
private static String applyShift(String string, Map shiftMap) {
StringBuilder sb = new StringBuilder();
for (char c : string.toCharArray()) {
// If a "shifted" value exists, use it, otherwise keep the original char
if (shiftMap.get(c) != null) {
sb.append(shiftMap.get(c));
} else {
sb.append(c);
}
}
return sb.toString();
}
private static Map<Character, Character> getShiftMap(KeyboardLayout layout) {
// Map to hold our entire keyboard layout
Map<Character, Character> shiftMap = new HashMap<>();
// Here we would need to map each and every key that has a "shifted" value. Capital letters would not need to
// be accounted for as they are already "shifted"
switch (layout) {
case QWERTY:
shiftMap.put('h', 'H');
shiftMap.put('e', 'E');
shiftMap.put('l', 'L');
shiftMap.put('o', 'O');
shiftMap.put('1', '!');
shiftMap.put('2', '@');
shiftMap.put('3', '#');
// Etc, etc, etc
}
return shiftMap;
}
}
The printed output for this example is HELLO!@#
.
In order to handle the opposite (find the UN-shifted character), you would need to either create and maintain another Map
, or use a 3rd-party API, such as Google's Guava library and their BiMap.
Upvotes: 1