Java格式化字符串替换特殊字符

时间:2015-09-02 04:49:43

标签: java string

我有这样的字符串:

String strCustom1 = "Red, Green, Blue";

我试过这个,但用“,

替换所有and
    strCustom = "Red, Green, Blue";
    strCustom = strCustom.replaceAll(",",  " and");

    [or]

    strCustom = strCustom.replace(",",  " and");

像这样:

    Red and Blue and Green

但我只想替换最后,space+and

所以看起来应该是这样的:

    Red, Green and Blue

以同样的方式,想要格式化:

    String strCustom2 = "Red, Green, Blue, Yellow";

因此我想得到这个:

    Red, Green, Blue and Yellow

3 个答案:

答案 0 :(得分:2)

您可以这样做:

strCustom = strCustom.substring(0, strCustom.lastIndexOf(",")) + " and" + strCustom.substring(strCustom.lastIndexOf(",") + 1);

答案 1 :(得分:1)

你可以尝试这样的事情......

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:descendantFocusability="blocksDescendants">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/station_name"
        android:padding="10dp"
        android:textColor="#eee345"
        android:textAppearance="?android:textAppearanceLarge"
        />

    <ImageButton android:id="@+id/favorite"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"

        android:background="#00ffffff"
     />


</LinearLayout>

Out put:

String strCustom = "Red, Green, Blue";
StringBuilder sb=new StringBuilder(strCustom);
sb.replace(strCustom.lastIndexOf(","),strCustom.lastIndexOf(",")+1," and");
System.out.println(sb.toString());

答案 2 :(得分:1)

快速正则表达式将为您完成:

    public static void main(String arf[]) {
        String strCustom1 = "Red, Green, Blue";
        System.out.println(strCustom1.replaceAll(",(?=\\s\\w+$)"," and" )); // find the last ",".
    }

O / P:

Red, Green and Blue