Tutorial Gateway

  • C
  • C#
  • Java
  • Python
  • SQL
  • MySQL
  • Js
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • Alteryx
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Python Programs
    • Java Programs

Java Program to Replace Last Character Occurrence in a String

by suresh

Write a Java Program to replace Last Character Occurrence in a String with an example. In this Java replace the last occurrence of a string character example, we used the toCharArray() to convert the repstCharStr to replastCharArr char array. 

Next, we used a While loop to iterate the repstCharStr string characters from end to start (reverse). Within the loop, we are comparing each character in the replastCharArr array with the replace_ch. If they are equal, we assigned new_ch in that replastCharArr index position followed by break statement to exit from the While loop.

import java.util.Scanner;

public class ReplaceLastCharOccur1 {
	private static Scanner sc;
	public static void main(String[] args) {
		String repstCharStr;
		char replace_ch, new_ch;
		
		sc= new Scanner(System.in);

		System.out.print("\nEnter a String to replace last Char Occurrence =  ");
		repstCharStr = sc.nextLine();
		
		System.out.print("\nEnter a Character to Replace =  ");
		replace_ch = sc.next().charAt(0);
		
		System.out.print("\nEnter a New Character =  ");
		new_ch = sc.next().charAt(0);
		
		char[] replastCharArr = repstCharStr.toCharArray();
		int i = replastCharArr.length - 1;
		while(i >= 0)
		{
			if(replastCharArr[i] ==  replace_ch) {
				replastCharArr[i] = new_ch;
				break;
			}
			i--;
		}
		System.out.format("\nAfter replacing Last Occurrence of %c with %c = ", replace_ch, new_ch);
		System.out.print(replastCharArr);
	}
}

OUTPUT

Java Program to Replace Last Character Occurrence in a String 1

This Java replace the last occurrence of a character example is the same as the above, and we replaced the While loop with For Loop.

import java.util.Scanner;

public class ReplaceLastCharOccur2 {
	private static Scanner sc;
	public static void main(String[] args) {
		String repstCharStr;
		char replace_ch, new_ch;
		
		sc= new Scanner(System.in);

		System.out.print("\nEnter a String to replace last Char Occurrence =  ");
		repstCharStr = sc.nextLine();
		
		System.out.print("\nEnter a Character to Replace =  ");
		replace_ch = sc.next().charAt(0);
		
		System.out.print("\nEnter a New Character =  ");
		new_ch = sc.next().charAt(0);
		
		char[] replastCharArr = repstCharStr.toCharArray();
		
		for(int i = replastCharArr.length - 1; i >= 0; i--)
		{
			if(replastCharArr[i] ==  replace_ch) {
				replastCharArr[i] = new_ch;
				break;
			}
		}
		System.out.format("\nAfter replacing Last Occurrence of %c with %c = ", replace_ch, new_ch);
		System.out.print(replastCharArr);
	}
}

OUTPUT

Java Program to Replace Last Character Occurrence in a String 2

Java Program to Replace Last Character Occurrence in a String Example 3

In Java Programming, we used the lastIndexOf to get the last index position of replace_ch in repstCharArr. Next, we assigned the new_ch at that position.

import java.util.Scanner;

public class ReplaceLastCharOccur3 {
	private static Scanner sc;
	public static void main(String[] args) {
		String repstCharStr;
		char replace_ch, new_ch;
		
		sc= new Scanner(System.in);

		System.out.print("\nEnter a String to replace last Char Occurrence =  ");
		repstCharStr = sc.nextLine();
		
		System.out.print("\nEnter a Character to Replace =  ");
		replace_ch = sc.next().charAt(0);
		
		System.out.print("\nEnter a New Character =  ");
		new_ch = sc.next().charAt(0);
		
		char[] repstCharArr = repstCharStr.toCharArray();;
		int i = repstCharStr.lastIndexOf(replace_ch);
		repstCharArr[i] = new_ch;

		System.out.format("\nAfter replacing Last Occurrence of %c with %c = ", replace_ch, new_ch);
		System.out.print(repstCharArr);
	}
}

RESULT

Java Program to Replace Last Character Occurrence in a String 3

We can use the Java String substring function to replace the last character occurrence. In this Java program, repstCharStr.lastIndexOf(replace_ch) finds the last index position. Next, repstCharStr.substring(0, i) returns substring up to i. Next, we added the new_ch to it. Then, we used another substring repstCharStr.substring(i + 1, repstCharStr.length() to concat string from i to end of that string.

import java.util.Scanner;

public class ReplaceLastCharOccur4 {
	private static Scanner sc;
	public static void main(String[] args) {
		String repstCharStr;
		char replace_ch, new_ch;
		
		sc= new Scanner(System.in);

		System.out.print("\nEnter a String to replace last Char Occurrence =  ");
		repstCharStr = sc.nextLine();
		
		System.out.print("\nEnter a Character to Replace =  ");
		replace_ch = sc.next().charAt(0);
		
		System.out.print("\nEnter a New Character =  ");
		new_ch = sc.next().charAt(0);
		
		int i = repstCharStr.lastIndexOf(replace_ch);
		String out = repstCharStr.substring(0, i) + new_ch + repstCharStr.substring(i + 1, repstCharStr.length() );

		System.out.format("\nAfter replacing Last Occurrence of %c with %c = ", replace_ch, new_ch);
		System.out.print(out);
	}
}

RESULT

Java Program to Replace Last Character Occurrence in a String 4

Java Program to Replace Last Character Occurrence in a String using StringBuilder

The Java StringBuilder also has the sb.lastIndexOf(String.valueOf(replace_ch)) but it accepts the string value so that we converted replace_ch to string. Next, deleteCharAt function removes the character. Then, sb.insert(j, new_ch) function insert the new_ch character at that position.

import java.util.Scanner;

public class ReplaceLastCharOccur5 {
	private static Scanner sc;
	public static void main(String[] args) {
		String repstCharStr;
		char replace_ch, new_ch;
		
		sc= new Scanner(System.in);

		System.out.print("\nEnter a String to replace last Char Occurrence =  ");
		repstCharStr = sc.nextLine();
		
		System.out.print("\nEnter a Character to Replace =  ");
		replace_ch = sc.next().charAt(0);
		
		System.out.print("\nEnter a New Character =  ");
		new_ch = sc.next().charAt(0);
		
		StringBuilder sb = new StringBuilder(repstCharStr);
		//int i = repstCharStr.lastIndexOf(replace_ch);
		int j = sb.lastIndexOf(String.valueOf(replace_ch));
		sb.deleteCharAt(j);
		sb.insert(j, new_ch);

		System.out.format("\nAfter "
				+ "replacing Last Occurrence of %c with %c = ", replace_ch, new_ch);
		System.out.print(sb);
	}
}

RESULT

Java Program to Replace Last Occurrence of a Character in a String 5

The Java StringBuffer also has the lastIndexOf, deleteCharAt, insert functions. So, we used those functions to replace the last occurrence of a character in a string.

import java.util.Scanner;

public class ReplaceLastCharOccur6 {
	private static Scanner sc;
	public static void main(String[] args) {
		String repstCharStr;
		char replace_ch, new_ch;
		
		sc= new Scanner(System.in);

		System.out.print("\nEnter a String to replace last Char Occurrence =  ");
		repstCharStr = sc.nextLine();
		
		System.out.print("\nEnter a Character to Replace =  ");
		replace_ch = sc.next().charAt(0);
		
		System.out.print("\nEnter a New Character =  ");
		new_ch = sc.next().charAt(0);
		
		StringBuffer sbuff = new StringBuffer(repstCharStr);
		//int i = repstCharStr.lastIndexOf(replace_ch);
		
		int j = sbuff.lastIndexOf(String.valueOf(replace_ch));
		sbuff.deleteCharAt(j);
		sbuff.insert(j, new_ch);

		System.out.format("\nAfter "
				+ "replacing Last Occurrence of %c with %c = ", replace_ch, new_ch);
		System.out.print(sbuff);
	}
}

RESULT

Java Program to Replace Last Occurrence of a Character in a String 6

Placed Under: Java Programs

  • Java Hello World Program
  • Java Add Two Numbers Program
  • Java Compound Interest Program
  • Java Number Divisible by 5 & 11
  • Java Cube of a Number Program
  • Java Print Even Numbers 1 to N
  • Java GCD of Two Numbers
  • Java LCM of Two Numbers
  • Java Largest of Two Numbers
  • Java Largest of Three Numbers
  • Java Print Multiplication Table
  • Java Odd Numbers from 1 to N
  • Java Odd Even Program
  • Java find +Ve or -Ve number
  • Java Power of a Number Program
  • Java Calculate Profit or Loss
  • Java Print 1 to 100 without Loop
  • Java Quadratic Equation roots
  • Java Square of Number Program
  • Java Simple Interest Program
  • Java Sum of Even Numbers
  • Java Sum of Odd numbers
  • Java Sum of Even & Odd Number
  • Java find Total ,Average & Percentage of 5 Subjects
  • Java ASCII Value of a Character
  • Java ASCII Value of all Characters
  • Java String Comparison program
  • Java Area of Circle Program
  • Java Area Of Triangle Program
  • Java Area Of Trapezoid Program
  • Java Area of Equilateral Triangle
  • Java Area of Rectangle Program
  • Java Area of Right angle triangle
  • Java Volume & Surface of Sphere
  • Java Volume & Surface of Cone
  • Java Volume & Surface of Cuboid
  • Java Volume & Surface of Cube
  • Java Cylinder Volume & Surface
  • Java Math Library
  • Java Armstrong Number Program
  • Java Perfect Number Program
  • Java Palindrome Program
  • Java Count Digits in a Number
  • Java Calculate Electricity Bill
  • Java Find Factors of a Number
  • Java Factorial Program
  • Java Fibonacci Series program
  • Java find First Digit of a Number
  • Java find Last Digit of a Number
  • Java First & Last Digit of Number
  • Java Generic Root of Number
  • Java Natural Numbers in Reverse
  • Java Natural Numbers from 1 to N
  • Java Find Sum of Prime Numbers
  • Java Print Prime Numbers 1 to N
  • Java Prime Number Program
  • Java Reverse a Number Program
  • Java Strong Number Program
  • Java Sum of N Natural Numbers
  • Java Sum of Digits Program
  • Java Swap Two Numbers
  • Java Leap Year Program
  • Java Number of Days in a Month
  • Java Array
  • Java Array Arithmetic Operations
  • Java Program to Copy an Array
  • Java Count Array Duplicates
  • Java count even number in array
  • Java count odd numbers in Array
  • Java Count Even & Odds in Array
  • Java Count Negative Array Items
  • Java Count Positive Array Items
  • Java Count Array +Ve & -Ve num
  • Java Delete Array Duplicates
  • Java Large & Small Array Item
  • Java Largest Array Number
  • Java Print Array Elements
  • Java Print Positive Array Items
  • Java Print Negative Array Items
  • Java Smallest Array Number
  • Java Second Largest Array Item
  • Java Print Unique Array Items
  • Java +Ve & -Ve in separate array
  • Java Sort Array in Descending
  • Java Sort Array in Ascending
  • Java Sum of Array Elements
  • Java Sum of Array Even Numbers
  • Java Sum of Array Odd Numbers
  • Java Sum of Array Even and Odd
  • Java Swap Arrays without temp
  • Java Matrix Introduction
  • Java Print Matrix items
  • Java Check 2 Matrices are Equal
  • Java Matrix Arithmetic operation
  • Java Matrix Addition
  • Java Matrix Multiplication
  • Java Find Matrix Determinant
  • Java Identity Matrix
  • Java Interchange Matrix diagonal
  • Java Matrix Lower Triangle
  • Java Matrix Lower Triangle Sum
  • Java Matrix Upper Triangle
  • Java Matrix Upper Triangle Sum
  • Java Scalar Matrix Multiplication
  • Java Sparse Matrix
  • Java Sum of Matrix Diagonal
  • Java Sum of Matrix Opp Diagonal
  • Java Sum of each Matrix Row
  • Java Sum of each Matrix Column
  • Java Sum of Matrix row & column
  • Java Symmetric Matrix
  • Java Transpose Matrix
  • Java Rectangle Star Pattern
  • Java Square Star Pattern
  • Java Hollow Box Number Pattern
  • Java Box Number Pattern of 1, 0
  • Java Square Number Pattern
  • Java Print Floyd’s Triangle
  • Java Print String Characters
  • Java String replace 1st Char Occ
  • Java String replace last Char occ
  • Java String remove 1st Char Occ
  • Java string remove last Char Occ
  • Java String remove 1st, last char
  • Java String remove all char occur
  • Java String Find 1st Char Occur
  • Java String find all char occur
  • Java String Find Last Char Occur
  • Java String Print 1st & last Char
  • Java String Chars ASCII values
  • Java Program to Concat Strings
  • Java String Characters count
  • Java Count Total Char Occur
  • Java Max Occur String Character
  • Java Toggle String Characters
  • Java Frequency of each Char
  • Java Count Vowels & Consonants
  • Java Count alph digits, special
  • Java Palindrome String
  • Java Program to Reverse a String
  • Java Min Occur String character
  • Java Convert Lower to Upper
  • Java Convert Upper to Lower
  • Java Count total String words
  • C Tutorial
  • C# Tutorial
  • Java Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQL Tutorial
  • SQL Server Tutorial
  • R Tutorial
  • Power BI Tutorial
  • Tableau Tutorial
  • SSIS Tutorial
  • SSRS Tutorial
  • Informatica Tutorial
  • Talend Tutorial
  • C Programs
  • C++ Programs
  • Java Programs
  • Python Programs
  • MDX Tutorial
  • SSAS Tutorial
  • QlikView Tutorial

Copyright © 2021 | Tutorial Gateway· All Rights Reserved by Suresh

Home | About Us | Contact Us | Privacy Policy