【问题标题】:Substring removes forward slash?子字符串删除正斜杠?
【发布时间】:2012-08-29 01:46:04
【问题描述】:
text = Daily 10 am - 5 pm.\\nClosed Thanksgiving and Christmas.

private String activateNewlines( String text ) {
        String temp = text;
        if ( text.contains( "\\n") ) {
            while ( temp.contains( "\\n" ) ) {
                int index = temp.indexOf( "\\n" );
                temp = temp.substring( 0, index ) + temp.substring( index + 1 );
            }
            return temp;
        }

        return text;
    }

我正在尝试为特殊字符删除额外的斜杠,但由于某种原因,子字符串最终会删除正斜杠。子字符串不喜欢字符串开头的斜线吗?最后的字符串变成了

Daily 10 am - 5 pm.nClosed Thanksgiving and Christmas.

我需要的是

Daily 10 am - 5 pm.\nClosed Thanksgiving and Christmas.

编辑:最终对我有用的东西:

    String temp = text;
    if ( text.contains( "\\n") ) {
        temp = temp.replaceAll( "\\\\n", "\\\n" );
        int x = 5;
        return temp;
    }

    return text;

这实际上允许 TextView 识别换行符。

【问题讨论】:

    标签: android string substring


    【解决方案1】:

    我认为你应该简单地这样做,

    string.replaceAll("\\n", "\n")
    

    详细代码,

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        String text = "Daily 10 am - 5 pm.\\nClosed Thanksgiving and Christmas.";
        Log.d("TEMP", "*********************************" + activateNewlines(text));
    
    }
    
    private String activateNewlines( String text ) {
        String temp = text;
    
        return temp.replaceAll("\\n", "\n");
    }
    

    Logcat 输出是,

      08-28 19:16:00.944: D/TEMP(9739): *********************************Daily 10 am - 5 pm.\nClosed Thanksgiving and Christmas.
    

    【讨论】:

    • 是的,我确实尝试过,但令人惊讶的是,在调试器中检查值后没有任何变化。
    • 我刚才跑了。它工作正常。我为你编辑了源代码。
    • 奇怪的是,我不知道为什么,replaceAll("\\n", "\n") 对我不起作用。最终奏效的是一个较早的解决方案(虽然海报删除了它),请参阅原始帖子。
    【解决方案2】:

    我有点困惑,但这里是。所以,"\n" 是一个新行。 "\\n" 是一个反斜杠和一个 n,\n。您可以使用 replaceAll 来摆脱它:string.replaceAll("\n", "")。这是我感到困惑的地方,我不确定你到底想要什么。如果你想保留新行,那么你必须从你得到它的任何地方正确地获取它(例如,你应该得到一个 \n 字符而不是转义的版本。)。

    【讨论】:

    • 我的程序中的一个字符串包含“\\n”,但我想用“\n”替换那些,希望当我设置 TextView.setText 时它会识别换行符并实际绘制字符换行符。全部替换似乎不起作用。我查看了 temp = replaceAll(...) 之后的值,没有任何内容被替换。
    • 嗯 那么@VendettaDroid 建议的(string.replaceAll("\\n", "\n"))应该可以工作。除非字符串实际上是别的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 2012-07-18
    • 2021-09-14
    相关资源
    最近更新 更多