文字の折り返しを使用して、ユーザー入力に基づいて文字列を変更する方法を見つけようとしています。文字列が「ボブは建物を建てるのが大好き」で、ユーザーがすべての文字 B/b を T/t に置き換えることを選択した場合、「トムは tuildings を組み立てるのが大好き」を取得するにはどのようにコーディングする必要がありますか?
3 に答える
1
String クラスの組み込みの置換機能があると思います。
String text = "Bob loves to build building";
text = text.replace("B","T").replace("b","t");
このようなもの ?
于 2012-09-13T05:15:06.853 に答える
0
String.replace(char, char)
簡単なスタートは、Javaについて知ることです。
// This addresses the example you gave in your question.
str.replace('B', 'T').replace('b', 't');
次に、ユーザー入力を toReplace および replaceWith 文字に取り込み、ASCII コードを使用して大文字/小文字の対応部分を見つけ出し、上記の replace メソッド呼び出しの引数を生成する必要があります。
public class Main
{
public static void main(String[] arg) throws JSONException
{
String str = "Bob loves to build building";
Scanner scanner = new Scanner(System.in);
char toReplace = scanner.nextLine().trim().charAt(0);
char replaceWith = scanner.nextLine().trim().charAt(0);
System.out.println(str.replace(getUpper(toReplace), getUpper(replaceWith)).replace(getLower(toReplace),
getLower(replaceWith)));
}
private static char getUpper(char ch)
{
return (char) ((ch >= 'A' && ch <= 'Z') ? ch : ch - ('a' - 'A'));
}
private static char getLower(char ch)
{
return (char) ((ch >= 'A' && ch <= 'Z') ? ch + ('a' - 'A') : ch);
}
}
于 2012-09-13T05:18:28.253 に答える
0
あなたの質問は不明です (Bob -> Tom で 'b' が 'm' になる方法は?)。ただし、大文字と小文字を区別しない置換を実行するには、次のようにする必要があります。
String text ="Bob loves to build building";
String b = "b";
Pattern p = Pattern.compile(b, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(text);
String outText = m.replaceAll("T");
于 2012-09-13T05:24:46.697 に答える