[英]Replace String with character code in Java
無法弄清楚如何用Java中的字符替換字符串。 我想要一個像這樣的函數:
replace(string, char)
但是在Java中沒有這樣的功能。
String str = str.replace("word", '\u0082');
String str = str.replace("word", (char)130);
我該怎么做?
使用字符串作為替換,恰好只有一個字符長度:
String original = "words";
String replaced = original.replace("word", "\u0130");
replaced
實例將等同於“İs”。
另請注意,根據您的問題, '\İ'
和(char)130
不是相同的字符。
\\u\u003c/code>語法使用十六進制 ,您的強制轉換使用十進制表示法。
你在Java中要求一個"function"
,你總是可以創建一個像這樣的method
public static String replace (String text, char old, char n){
return text.replace(old, n);
}
然后你可以根據需要調用這個method
String a = replace("ae", 'e', '3');
在這種情況下, method
將返回一個String
以a3
為值,但可以更換不僅是一個char
由另一個,你可以替換String
與多個字符以同樣的方式
public static String replace (String text, String old, String n){
return text.replace(old, n);
}
然后你這樣調用這個method
String a = replace("aes", "es", "rmy");
結果將是一個以army
為價值的String
非常簡單:
String orginal = "asdf";
char replacement = 'z';
orginal = original.replace(original, replacement+"");
“字符串是一系列字符”
String s="hello";
char c='Y';
System.out.println(s.replace(s, Character.toString(c)));
Output:
Y
最簡單的方法:
"value_".replace("_",String.valueOf((char)58 )); //return "value:"
編輯:
(char)58 //return: ':'
(int)':' //return: 58
由於我們希望使用代碼而不使用字符,因此我們必須將代碼傳遞給字符
要解決的另一個問題是方法“replace” 不帶“(String x,char y)”
所以我們通過這種方式將字符傳遞給String:
String.valueOf((char)58) //this is a String like this ":"
最后我們從int代碼中獲取String,進行替換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.