Delete everything after part of a string

2020-02-05 01:25发布

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!

10条回答
兄弟一词,经得起流年.
2楼-- · 2020-02-05 01:52

For example, you could do:

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

or

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

(and add relevant error handling)

查看更多
▲ chillily
3楼-- · 2020-02-05 01:54

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;
}`
查看更多
欢心
4楼-- · 2020-02-05 01:58

The apache commons StringUtils provide a substringBefore method

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

查看更多
看我几分像从前
5楼-- · 2020-02-05 01:58

Perhaps thats what you are looking for:

String str="Stack Overflow - A place to ask stuff";

String newStr = str.substring(0, str.indexOf("-"));
查看更多
够拽才男人
6楼-- · 2020-02-05 01:58

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

查看更多
Summer. ? 凉城
7楼-- · 2020-02-05 01:58

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"
查看更多
登录 后发表回答