【问题标题】:Don't change replace with string Java不要用字符串 Java 更改替换
【发布时间】:2017-02-06 11:32:00
【问题描述】:

我写了一个提取最后六个字符的程序 这是我的代码

String numberString;
int number=123456;

// convert int to string
numberString = String.valueOf(number);
char[] chars = new char[7];
String napis = "S4P6W7M522SC3OXX55K3NN77666N34M2";
char[] array = napis.toCharArray();

// loop which pulls the last six characters
int index = 0;
for (int i = 0; i < array.length; i++) {
    if (i >= 26 && i <= 32) {
        chars[index] = array[i];
        index++;
    }

}

String Str = new String(napis);
System.out.print("String: " + napis);
// convert char to string
String kod = String.valueOf(chars);
System.out.print("Result " + kod);
// show new String
String newString = napis.replace(kod, numberString);
System.out.print("New String: " + newString);

//显示输出

Please write  six number
    123456
    String: S4P6W7M522SC3OXX55K3NN77666N34M2
    Result 6N34M2
    New String: S4P6W7M522SC3OXX55K3NN77666N34M2

应该是

    New String: S4P6W7M522SC3OXX55K3NN7766123456

我不知道为什么替换是不正确的

【问题讨论】:

  • 为什么不简单地使用子字符串来删除最后 6 个字符?请定义Character ;)
  • 为什么你认为numberString 是123456?你能在替换之前输出numberStringnumber吗?

标签: java string replace char


【解决方案1】:

您的问题是您使用的是 7 个字符的数组,如果您使用此数组检查您构建的字符串 (kod) 的长度,您将得到 7 个字符,因此它无法匹配子字符串您正在尝试替换仅执行 6 个字符的操作。 (你最后有 0 字符(值,而不是数字)

使用 6 个数组

 char[] chars = new char[6];

为了防止这个问题。


如果您的字符串短于 32 个字符,这有点冒险。您可以简单地从末尾读取数组,并且只读取 6 个字符(或直到您到达索引 0)


但您也可以在字符串中的其他位置包含最后 6 个字符序列。这也将替换第一个序列(如果您使用replaceAll())或仅用当前代码替换第一个序列


使用子字符串删除最后 6 个字符会更简单、更安全。

只需要确保您将拥有至少 6 个字符的字符串,诀窍是使用 Math.max :

napis.substring(0, Math.max(napis.length() - 6, 0)) + numberString;

Math.max 只会在字符串太短时给出 0。

【讨论】:

  • @Paulina,请记住,原始数组 (char/int/double) 将单元格默认设置为 0,因此您的字符串类似于 "6N34M2"0
  • @Paulina,如果适合您,请不要忘记接受答案。请参阅 tour 以了解 StackOverflow 的工作原理。
【解决方案2】:

这是解决方案的简单方法。

import java.util.Scanner;
class replace {
    public static void main(String args[]) {
        Scanner s=new Scanner(System.in);
        int a=s.nextInt();
        String aa=Integer.toString(a);
        String b=s.next();
        String bb=b.substring(b.length()-6);
        System.out.println(aa+" "+bb);
        String bc=b.replace(bb,aa);
        System.out.println(bc);
     }

}   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-27
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 2015-11-13
    • 1970-01-01
    • 2013-07-09
    相关资源
    最近更新 更多