I have been having trouble with a certain code problem, where I have to Create a method that receives a String and returns the String converted into shorthand. I'm not allowed to use the replace functions and I don't really know how to use arrays yet.
I have to fit according to these standards:
A.replace these four words: "and" with "&", "to" with "2", "you" with "u", and "for" with "4" whenever they appear as separate words within a sentence.
B.remove all vowels ('a', 'e', 'i', 'o', 'u'), whether lowercase or uppercase, unless the vowel appears by itself.
For example, For I shall love you forever
becomes 4 I shll lv u frvr
here is my code in progress, I haven't necessarily started since I don't know how to approach the problem.
public static String shortHand(String str){
/* strategy:
* take string length. do a for loop for each individual letter and then search for letters and, replace
* with &, look for to, replace with 2, replace you w/ u, and then take out any vowels.
*/
for(int i = str.length(); i < str.length(); i++){
str.toLowerCase();
}
return "";
}
It would be helpful if I could find a solution that utilizes helper methods, but not mandatory.
Try HashMap to store key and value pair. In your question , store word to be replaced as a key ie "and" and value should be '&'.
create Set of vowels to check against whether it is vowel or not. Try below program.
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Test {
private static final Map<String, Character> keyMap = new HashMap<String, Character>(); // store key and value
private static final Set<Character> vowelSet = new HashSet<Character>(); // store vowel in set
static {
keyMap.put("and", '&');
keyMap.put("to", '2');
keyMap.put("you", 'u');
keyMap.put("for", '4');
vowelSet.add('a');
vowelSet.add('e');
vowelSet.add('i');
vowelSet.add('o');
vowelSet.add('u');
}
public static void main(String[] args) {
System.out.println(shortHand("For I shall love you forever"));
}
public static String shortHand(String str) {
StringBuffer result = new StringBuffer();
String[] strArr = str.split(" "); //seperate string by the space
for (int i = 0; i < strArr.length; i++) {
String temp = strArr[i].toLowerCase();
if (keyMap.containsKey(temp)) {//check in map eg. does it contains in the map then replace it with shorthand word.
result.append(keyMap.get(temp));
result.append(" ");
} else {
if (temp.length() == 1 && vowelSet.contains(temp.charAt(0))) {//if it is only a vowel
result.append(temp);
result.append(" ");
} else {
for (int j = 0; j < temp.length(); j++) {//check in every character if its vowel or not
if (!vowelSet.contains(temp.charAt(j))) {
result.append(temp.charAt(j));
}
}
result.append(" ");
}
}
}
return result.toString();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.