从Java字符串中删除行尾字符 [英] Remove end of line characters from Java string

查看:143
本文介绍了从Java字符串中删除行尾字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的字符串

"hello
java
book"

我想从字符串中删除\ r和\ n(hello \\\\\\ nn )。我想要一个字符串作为hellojavabook。我怎么能这样做?

I want remove \r and \n from string(hello\r\njava\r\nbook). I want a string as "hellojavabook". How can I do this?

推荐答案

正则表达式与replaceAll。

Regex with replaceAll.

public class Main
{
    public static void main(final String[] argv) 
    {
        String str;

        str = "hello\r\njava\r\nbook";
        str = str.replaceAll("(\\r|\\n)", "");
        System.out.println(str);
    }
}

如果您只想删除\\\当它们成对时(上面的代码删除了\r或\ n)代替:

If you only want to remove \r\n when they are pairs (the above code removes either \r or \n) do this instead:

str = str.replaceAll("\\r\\n", "");

这篇关于从Java字符串中删除行尾字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆