[英]Replacing digits with dashes in the given string
我试图理解为什么这段代码不起作用。
编写一个代码,用给定字符串中的破折号替换数字。 字母保持不变。
我的代码:
导入 java.util.Scanner; 公共类 JavaApp {
public static void main(String[] args) {
Scanner vstup = new Scanner(System.in);
String a = vstup.nextLine();
String b = "";
for (int index=0;index<10;index++) {
b= (a.replace('0','-'));
b= (a.replace('1','-'));
b= (a.replace('2','-'));
b= (a.replace('3','-'));
b= (a.replace('4','-'));
b= (a.replace('5','-'));
b= (a.replace('6','-'));
b= (a.replace('7','-'));
b= (a.replace('8','-'));
b= (a.replace('9','-'));
}
System.out.println(b);
} }
反馈赞赏:)
首先,您不要修改a
。 它将始终包含您的输入。 每次调用replace
都会创建一个新的 String 并返回修改后的值。 a
保持不变,仍然包含旧值。 连续多次分配b
意味着b
将只包含从最后一个调用的replace
创建的最后一个 String 。 在你的情况下b = a with dash instead of 9
因为你替换的最后一件事是'9'。 0-8 的数字仍将包含在b
因为它们永远不会从a
删除。
其次,你这样做的方式是正确的,但你选择了艰难的路线。 字符串支持使用正则表达式。 如果您不了解它们,请查看它们。 它们允许定义可以与输入匹配的逻辑字符集。 因此,换句话说,您可以定义一个匹配任何数字的正则表达式并替换输入中的所有结果。 像这样
String numberRegex = "\\d";
String replaceValue = "-";
String result = input.replaceAll(numberRegex, replaceValue); // replaces all findings that match the regex with the replaceValue
要使您的非正则表达式版本正常工作,您必须对已删除其他值的字符串调用 replace。 像这样
String result = input;
result = result.replace('0', '-');
result = result.replace('1', '-');
// .....
或者您只是将它们链接起来以使其更具可读性。 您可以直接对上次替换返回的值调用替换。
String result = input.replace('0', '-').replace('1', '-').replace....);
尝试这个:
b= (a.replaceAll("\\d","-"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.