2011-12-17 84 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*" 
相关问题