gpt4 book ai didi

java - 用 "*"替换最后 4 个字符

转载 作者:搜寻专家 更新时间:2023-11-01 01:02:26 24 4
gpt4 key购买 nike

我有一个字符串,我需要用“*”符号替换字符串的最后 4 个字符。谁能告诉我怎么做。

最佳答案

一种快速简便的方法...

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) + "****";
}
}

关于java - 用 "*"替换最后 4 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8544234/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com