我有一個字符串,我需要用「*」符號替換字符串的最後4個字符。任何人都可以告訴我如何去做。用「*」替換最後4個字符
-2
A
回答
6
一個快速簡便的方法...
public static String replaceLastFour(String s) {
int length = s.length();
//Check whether or not the string contains at least four characters; if not, this method is useless
if (length < 4) return "Error: The provided string is not greater than four characters long.";
return s.substring(0, length - 4) + "****";
}
現在,所有你需要做的就是調用replaceLastFour(String s)
一個字符串作爲參數,如下所示:
public class Test {
public static void main(String[] args) {
replaceLastFour("hi");
//"Error: The provided string is not greater than four characters long."
replaceLastFour("Welcome to StackOverflow!");
//"Welcome to StackOverf****"
}
public static String replaceLastFour(String s) {
int length = s.length();
if (length < 4) return "Error: The provided string is not greater than four characters long.";
return s.substring(0, length - 4) + "****";
}
}
1
也許一個例子有助於:
String hello = "Hello, World!";
hello = hello.substring(0, hello.length() - 4);
// hello == "Hello, Wo"
hello = hello + "****";
// hello == "Hello, Wo****"
1
public class Model {
public static void main(String[] args) {
String s="Hello world";
System.out.println(s.substring(0, s.length()-4)+"****");
}
}
1
您可以使用s爲此。
String str = "mystring";
str = str.substring(0,str.length()-4);
str = str + "****";
所以substring有兩個參數。
substring(beginIndex, endIndex);
所以,如果你調用一個子方法在一個字符串,它創建了一個新的字符串,從beginIndex包容性和endIndex獨家開始。例如:
String str = "roller";
str = str.substring(0,4);
System.out.Println("str");
OUTPUT :
roll
所以範圍從beginIndex開始,直到endIndex - 1的
如果您想了解更多關於子,請訪問http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html
希望這有助於。
0
最簡單的就是使用正則表達式:
String s = "abcdefg"
s = s.replaceFirst(".{4}$", "*"); => "abc*"
相關問題
- 1. 替換最後一個字符
- 2. 使用JavaScript替換字符串的最後一個字符
- 3. 替換最後一個字
- 4. 替換字符串中的最後一個字符
- 5. 替換4個不同的字符
- 6. JavaScript不替換字符串的最後一個符號
- 7. php 5個字符替換文字後?
- 8. Javascript/jQuery - 替換字符串中最後一個字的出現
- 9. 替換字符串數組中的最後一個字母Javascript
- 10. 替換字符串中的最後一個字
- 11. 如何用VB6替換字符串中的最後一個字符?
- 12. 用jquery/regex替換子字符串中的最後一個匹配的字符
- 13. 使用正則表達式或DOMDocument替換最後一個字符(字符串)
- 14. C#用字符串中的另一個替換最後一個字母
- 15. 替換字符串中最後出現的子字符串
- 16. 替換字符串中最後一次出現的字符
- 17. Javascript:替換後的字符_
- 18. GSUB替換最後一個字符串的長度不明的最後空間
- 19. 陣的字符串替換隻有最後一個元素
- 20. C#字符串數組替換最後一個元素
- 21. 替換文本文件中的最後一個字符(python)
- 22. 替換SQL Server 2008中的最後一個字符
- 23. 僅替換字符串的最後一個空格的問題
- 24. 如何用此字符串中的兩個不同字符替換第一個和最後一個字符「{0}」
- 25. 如何替換字符串中最後一個逗號的'&'字符?
- 26. Android:TextView自動截斷並替換字符串的最後3個字符
- 27. Base64Encoder切斷字符串的最後4個字符
- 28. 需要消除字符串中的最後4個字符(varchar)
- 29. 獲取最後4個字符的字符串
- 30. 替換模式後的字符串的最後一部分
你知道`String`的'子()`方法? – 2011-12-17 11:02:08