gpt4 book ai didi

java - Java 替换字符串中的子字符串

转载 作者:行者123 更新时间:2023-12-01 22:50:58 26 4
gpt4 key购买 nike

我正在尝试替换字符串中的多个子字符串,例如我有以下字符串wordlist

one    two    three

我想用 \r\n 新行字符替换 \t 制表符。

我将separator变量定义为\n,将replacement变量定义为\r\n

然后我使用 wordlist = wordlist.replaceAll(separator, replacement); 替换所有字符,但是当我再次显示 wordlist 时,它给出以下内容结果

onerntwornthree

我还尝试通过子字符串分隔符wordlist拆分为一个数组,然后将其再次逐字连接到一个由replacement<分隔的新字符串中,但它只是给了我一个结果

one\r\ntwo\r\nthree

有人知道如何解决这个问题吗?如果您需要,这里是完整代码:

System.out.print("Separator to replace: ");
separator = scanner.next( );

System.out.print("Replacement for separator: ");
replacement = scanner.next( );

wordlist = wordlist.replaceAll(separator, replacement);

最佳答案

您输入的制表符似乎不正确。

这段代码给出

    String wordlist="one    two three";
wordlist = wordlist.replaceAll("\t", "\r\n");
System.out.println(wordlist);

这个输出-

one
two
three

关于java - Java 替换字符串中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24736387/

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