Wednesday, 3 May 2023

Remove a suffix from given string in Java

Write a method such that it takes a string and suffix as argument and remove the suffix from given string.

 

Signature

public static String removeSuffix(final String inputStr, final String suffixToRemove)

Below snippet remove the given suffix from the string.

public static String removeSuffix(final String inputStr, final String suffixToRemove) {
	if (inputStr == null || inputStr.isEmpty() || suffixToRemove == null || suffixToRemove.isEmpty()) {
		return inputStr;
	}

	if (inputStr.endsWith(suffixToRemove)) {
		return inputStr.substring(0, inputStr.length() - suffixToRemove.length());
	}

	return inputStr;
}

Find the below working application.

 


SuffixRemovalDemo.java

package com.sample.app.strings;

public class SuffixRemovalDemo {

	public static String removeSuffix(final String inputStr, final String suffixToRemove) {
		if (inputStr == null || inputStr.isEmpty() || suffixToRemove == null || suffixToRemove.isEmpty()) {
			return inputStr;
		}

		if (inputStr.endsWith(suffixToRemove)) {
			return inputStr.substring(0, inputStr.length() - suffixToRemove.length());
		}

		return inputStr;
	}

	public static void main(String[] args) {
		String str = "Hello World";
		String suffixToRemove1 = "rld";
		String suffixToRemove2 = "aba";

		System.out.println("Result after removing the suffix '" + suffixToRemove1 + "' from '" + str + "' is : "
				+ removeSuffix(str, suffixToRemove1));

		System.out.println("Result after removing the suffix '" + suffixToRemove2 + "' from '" + str + "' is : "
				+ removeSuffix(str, suffixToRemove2));
	}
}

Output

Result after removing the suffix 'rld' from 'Hello World' is : Hello Wo
Result after removing the suffix 'aba' from 'Hello World' is : Hello World




 

Previous                                                 Next                                                 Home

No comments:

Post a Comment