Delete everything after part of a string

JavaAndroidStringReplace

Java Problem Overview


I have a string that is built out of three parts. The word I want the string to be (changes), a seperating part (doesn't change) and the last part which changes. I want to delete the seperating part and the ending part. The seperating part is " - " so what I'm wondering is if theres a way to delete everything after a certaint part of the string.

An example of this scenario would be if I wanted to turn this: "Stack Overflow - A place to ask stuff" into this: "Stack Overflow". Any help is appreciated!

Java Solutions


Solution 1 - Java

For example, you could do:

String result = input.split("-")[0];

or

String result = input.substring(0, input.indexOf("-"));

(and add relevant error handling)

Solution 2 - Java

The apache commons StringUtils provide a substringBefore method

StringUtils.substringBefore("Stack Overflow - A place to ask stuff", " - ")

Solution 3 - Java

Kotlin Solution

Use the built-in Kotlin substringBefore function (Documentation):

var string = "So much text - no - more"
string = string.substringBefore(" - ") // "So much text"

It also has an optional second param, which is the return value if the delimiter is not found. The default value is the original string

string.substringBefore(" - ", "fail")  // "So much text"
string.substringBefore(" -- ", "fail") // "fail"
string.substringBefore(" -- ")         // "So much text - no - more"

Solution 4 - Java

You can use this

String mysourcestring = "developer is - development";
String substring = mysourcestring.substring(0,mysourcestring.indexOf("-"));

it would be written "developer is -"

Solution 5 - Java

Perhaps thats what you are looking for:

String str="Stack Overflow - A place to ask stuff";
        
String newStr = str.substring(0, str.indexOf("-"));

Solution 6 - Java

I created Sample program for all the approches and SubString seems to be fastest one.

Using builder : 54
Using Split : 252
Using Substring  : 10

Below is the sample program code

            for (int count = 0; count < 1000; count++) {
		// For JIT
	}
	long start = System.nanoTime();
	//Builder
	StringBuilder builder = new StringBuilder(
			"Stack Overflow - A place to ask stuff");
	builder.delete(builder.indexOf("-"), builder.length());
	System.out.println("Using builder : " + (System.nanoTime() - start)
			/ 1000);
	start = System.nanoTime();
	//Split
	String string = "Stack Overflow - A place to ask stuff";
	string.split("-");
	System.out.println("Using Split : " + (System.nanoTime() - start)
			/ 1000);
	//SubString
	start = System.nanoTime();
	String string1 = "Stack Overflow - A place to ask stuff";
	string1.substring(0, string1.indexOf("-"));
	System.out.println("Using Substring : " + (System.nanoTime() - start)
			/ 1000);
	return null;

Solution 7 - Java

Clean way to safely remove until a string, and keep the searched part if token may or may not exist.

String input = "Stack Overflow - A place to ask stuff";
String token = " - ";
String result = input.contains(token)
  ? token + StringUtils.substringBefore(string, token)
  : input;
// Returns "Stack Overflow - "

> Apache StringUtils functions are null-, empty-, and no match- safe

Solution 8 - Java

This will do what you need:

newValue = oldValue.substring(0, oldValue.indexOf("-");

Solution 9 - Java

String line = "deltaasm:/u01/app/oracle/product/11.2.0/dbhome_1:N        # line addred by agent";

	String rep = "deltaasm:";
	String after = "";

	String pre = ":N";
	String aft = "";
	String result = line.replaceAll(rep, after);
	String finalresult = result.replaceAll(pre, aft);
	System.out.println("Result***************" + finalresult);

	String str = "deltaasm:/u01/app/oracle/product/11.2.0/dbhome_1:N        # line addred by agent";

	String newStr = str.substring(0, str.indexOf("#"));
	System.out.println("======" + newStr);

Solution 10 - Java

you can my utils method this action..

public static String makeTwoPart(String data, String cutAfterThisWord){
    String result = "";

    String val1 = data.substring(0, data.indexOf(cutAfterThisWord));

    String va12 = data.substring(val1.length(), data.length());

    String secondWord = va12.replace(cutAfterThisWord, "");

    Log.d("VAL_2", secondWord);

    String firstWord = data.replace(secondWord, "");

    Log.d("VAL_1", firstWord);

    result = firstWord + "\n" + secondWord;


    return result;
}`

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSweSnowView Question on Stackoverflow
Solution 1 - JavaassyliasView Answer on Stackoverflow
Solution 2 - JavaroemerView Answer on Stackoverflow
Solution 3 - JavaGiboltView Answer on Stackoverflow
Solution 4 - JavaslezadavView Answer on Stackoverflow
Solution 5 - JavawaqaslamView Answer on Stackoverflow
Solution 6 - JavaAmit DeshpandeView Answer on Stackoverflow
Solution 7 - JavaGiboltView Answer on Stackoverflow
Solution 8 - JavaDan D.View Answer on Stackoverflow
Solution 9 - JavaKailas KakadeView Answer on Stackoverflow
Solution 10 - JavaCaner YılmazView Answer on Stackoverflow