2011-12-17 82 views
-2

我有一個字符串,我需要用「*」符號替換字符串的最後4個字符。任何人都可以告訴我如何去做。用「*」替換最後4個字符

+1

你知道`String`的'子()`方法? – 2011-12-17 11:02:08

回答

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*" 
相關問題