简体   繁体   English

每当 java 中出现关键字时,如何在字符串中引入换行符?

[英]How to introduce line break in a string whenever keyword occurs in java?

Objective: prefix each keyword with new line in a string目标:在字符串中为每个关键字添加换行符

code snippet:代码片段:

String [] keys = {"Status:","Active:","Priority:"};
text="Status:   Open    Active: Yes Priority:   None";
System.out.println("Before: "+text);
for(int k = 0; k<keys.length; k++){
text = text.replaceAll(keys[k], "\r\n"+keys[k]);
}
System.out.println("After: "+text);

Expected Output:预期 Output:

[new line]
Status: Open    
Active: Yes 
Priority:   None

Actual Output:实际 Output:

[new line]
Status: Open    Active: Yes Priority:   None

Update: the text is copied from web page with charset utf-8, pasted in notepad and saved with encoding utf-8.更新:文本从 web 页面复制,字符集为 utf-8,粘贴在记事本中并以编码 utf-8 保存。 the text read by the program and unable to process.程序读取的文本无法处理。 the same string has been pasted, I think encoding is not preserved.粘贴了相同的字符串,我认为没有保留编码。

Please help me resolving the issue.请帮我解决问题。

The text contains \r\n but the way it is displayed does not show them.文本包含\r\n但它的显示方式不显示它们。

System.out.println print all on a single line, and at the end, this method insert a new line character. System.out.println将所有内容打印在一行上,最后,此方法插入一个换行符。

If you want to print out the modified text only for debug purpose, you can do this:如果您只想出于调试目的打印修改后的文本,您可以这样做:

System.out.println("After: " + text.replaceAll("\r\n", "\\r\\n");

It will print out the text with visibles \r\n .它将打印出可见的文本\r\n

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

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