Monday, October 12, 2015

java - How to perform string replace

MainActivity.java

package com.cfsuman.me.javaexamples;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get widget reference from XML layout
        TextView tv = (TextView) findViewById(R.id.tv);

        // Initialize a new Strings
        String stringOfColors = "Red green yellow black red black Green";
        tv.setText("String : " + stringOfColors);

        tv.setText(tv.getText()+"\n\nString replace character");
        // Replace a specified character from string
        // This will replace all 'b' characters from string with character 'B'
        String replacebWithB = stringOfColors.replace('b','B');
        tv.setText(tv.getText() + "\nString.replace('b','B') : " + replacebWithB);

        tv.setText(tv.getText()+"\n\nString replace substring");
        // Replace a specified substring from string
        // This will replace all 'black' string/substring from string with string 'BLACK'
        String replaceblackWithBLACK = stringOfColors.replace("black", "BLACK");
        tv.setText(tv.getText() + "\nString.replace(\"black\",\"BLACK\") : " + replaceblackWithBLACK);

        tv.setText(tv.getText()+"\n\nString replace case sensitive");
        // Replace a specified substring from string by respect case (case sensitive)
        // This will replace all 'green' string/substring from string with string 'GREEN'
        String replacegreenWithGREEN = stringOfColors.replace("green","GREEN");
        tv.setText(tv.getText() + "\nString.replace(\"green\",\"GREEN\") : " + replacegreenWithGREEN);

        tv.setText(tv.getText()+"\n\nString replace by ignoring case");
        // Replace a specified substring from string by ignoring case (case insensitive)
        // This will replace all 'green' string/substring from string with string 'GREEN'
        // String replace using regular expression
        String replacegreenWithGREENregex = stringOfColors.replaceAll("(?i)green", "GREEN");
        tv.setText(tv.getText() + "\nString.replaceAll(\"(?i)green\",\"GREEN\") : " + replacegreenWithGREENregex);
    }
}
More android examples