繁体   English   中英

如何使用Java将字符串中的所有字母替换为另一个字符?

[英]How do I replace all the letters in a string with another character using Java?

我希望能够用下划线字符替换字符串中的所有字母。

例如,假设我的字符串由字母字符“ Apple”组成。 因为苹果里面有五个字符(字母),我如何将其转换为五个下划线?

为什么不忽略“替换”的想法,而只创建一个带有相同下划线数量的新字符串...

String input = "Apple";

String output = new String(new char[input .length()]).replace("\0", "_");
//or
String output2 = StringUtils.repeat("_", input .length());

很大程度上是从这里开始的

正如许多其他人所说的那样,如果您不想包含空格,则replaceAll可能是解决之道。 为此,您不需要正则表达式的全部功能,但除非字符串绝对很大,否则肯定不会受到伤害。

//replaces all non-whitespace with "_"
String output3 = input.replaceAll("\S", "_");
        String content = "apple";
        String replaceContent = "";
        for (int i = 0; i < content.length(); i++)
        {
            replaceContent = replaceContent + content.replaceAll("^\\p{L}+(?: \\p{L}+)*$", "_");
        }

        System.out.println(replaceContent);

使用正则表达式

关于\\p{L} :参考Unicode正则表达式

您可以使用String.replaceAll()方法。

替换所有字母:

String originalString = "abcde1234";
String underscoreString = originalString.replaceAll("[a-zA-Z]","_");

如果您的意思是所有字符:

String originalString = "abcde1234";
String underscoreString = originalString .replaceAll(".", "_");

那这个呢

  public static void main(String args[]) {
    String word="apple";

        for(int i=0;i<word.length();i++) {
            word = word.replace(word.charAt(i),'_');
        }
        System.out.println(word);
}

试试这个。

String str = "Apple";
str = str.replaceAll(".", "_");
System.out.println(str);

尝试这个,

        String sample = "Apple";
        StringBuilder stringBuilder = new StringBuilder();
        for(char value : sample.toCharArray())
        {
            stringBuilder.append("_");
        }
        System.out.println(stringBuilder.toString());
stringToModify.replaceAll("[a-zA-Z]","_");

你可以做

int length = "Apple".length();
String underscores = new String(new char[length]).replace("\0", "_");

str.replaceAll("[a-zA-Z]","_");


    String str="stackoverflow";
    StringBuilder builder=new StringBuilder();
    for(int i=0;i<str.length();i++){
        builder.append('_');
    }
    System.out.println(builder.toString());

当然,我可以选择其他方法:

String input = "Apple";
char[] newCharacters = new char[input.length()];
Arrays.fill(newCharacters, '_');
String underscores = new String(newCharacters);

或者这是一种不错的递归方法:

public static void main(String[] args) {
    System.out.println(underscores("Apple"));
}

public static String underscores(String input) {
    if (input.isEmpty()) return "";
    else return "_" + underscores(input.substring(1));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM