Replace specific whole word in string Java Android example

How to change-override whole word inside a string with another word using string.replace() method.

Java gives us string replace function string.replace() to replace string words from a string and change the whole word as per user requirement. With this feature application developer can automatically find and replace banned words which user dose not want to show on screen with another ones. So here is the complete step by step tutorial for Replace specific whole word in string Java Android example.

android-project-download-code-button

How to Replace specific whole word in string Java Android example.

Code for MainActivity.java file.

 package com.replacespecificwordinstring_android_examples.com;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;


public class MainActivity extends Activity {
 
 TextView textview1,textview2;
 String beforeValue,afterValue;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 textview1 = (TextView)findViewById(R.id.textView1);
 textview2 = (TextView)findViewById(R.id.textView2);
 
 beforeValue = "Hello Dear" ;
 
 // Replacing small Dear with Friend .
 
 afterValue = beforeValue.replace("Dear","Friend");
 
 textview1.setText("Before Replace = " + beforeValue) ;
 textview2.setText("After Replace = " + afterValue) ;
 
 }
}

Code for activity_main.xml layout file.

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.replacespecificwordinstring_android_examples.com.MainActivity" >
 
 <TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentTop="true"
 android:layout_centerHorizontal="true"
 android:text="Before Replace"
 android:gravity="center"
 android:textAppearance="?android:attr/textAppearanceLarge" />

 <TextView
 android:id="@+id/textView2"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/textView1"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="22dp"
 android:gravity="center"
 android:text="After Replace"
 android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Screenshot :

Replace specific whole word in string Java Android example

Click here to download Replace specific whole word in string Java Android example project with source code.

Leave a Reply

Your email address will not be published. Required fields are marked *