Wednesday 3 May 2023

Remove a prefix from given string in Java

Write a method such that it takes a string and prefix as arguments and remove the prefix from given string.

 

Signature

public static String removePrefix(final String inputStr, final String prefixToRemove)

 

Below snippet remove the given prefix from input string.

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

	if (inputStr.startsWith(prefixToRemove)) {
		return inputStr.substring(prefixToRemove.length());
	}
	return inputStr;
}

Find the below working application.


PrefixRemovalDemo.java

package com.sample.app.strings;

public class PrefixRemovalDemo {
	public static String removePrefix(final String inputStr, final String prefixToRemove) {
		if (inputStr == null || inputStr.isEmpty() || prefixToRemove == null || prefixToRemove.isEmpty()) {
			return inputStr;
		}

		if (inputStr.startsWith(prefixToRemove)) {
			return inputStr.substring(prefixToRemove.length());
		}
		return inputStr;
	}

	public static void main(String[] args) {
		String str = "Hello World";
		String prefixToRemove1 = "He";
		String prefixToRemove2 = "aba";

		System.out.println("Result after removing the prefix '" + prefixToRemove1 + "' from '" + str + "' is : "
				+ removePrefix(str, prefixToRemove1));

		System.out.println("Result after removing the prefix '" + prefixToRemove2 + "' from '" + str + "' is : "
				+ removePrefix(str, prefixToRemove2));
	}
}

Output

Result after removing the prefix 'He' from 'Hello World' is : llo World
Result after removing the prefix 'aba' from 'Hello World' is : Hello World

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment