[英]Java Making a string shorthand/No replace() function allowed/static method
我在某些代碼問題上遇到了麻煩,我必須創建一個方法來接收一個String並將返回的String轉換為簡寫形式。 我不允許使用替換功能,而且我還真的不知道如何使用數組。
我必須符合以下標准:
答:只要它們在句子中作為單獨的單詞出現,就用這四個詞替換:“和”和“&”,“到”和“ 2”,“ you”和“ u”以及“ for”和“ 4”。
B.刪除所有小寫或大寫的元音(“ a”,“ e”,“ i”,“ o”,“ u”),除非元音單獨出現。
例如, For I shall love you forever
變成4 I shll lv u frvr
這是我的代碼在進行中,因為我不知道如何解決該問題,所以不一定要開始。
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 "";
}
如果我可以找到一個使用輔助方法但不是強制性的解決方案,那將很有幫助。
嘗試使用HashMap來存儲鍵和值對。 在您的問題中,將要替換的單詞存儲為鍵,即“和”,值應為“&”。
創建元音集以檢查是否為元音。 請嘗試以下程序。
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.