Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete everything after part of a string

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!

like image 448
SweSnow Avatar asked Sep 05 '12 08:09

SweSnow


People also ask

How do you delete everything after a certain character?

Press Ctrl + H to open the Find and Replace dialog. In the Find what box, enter one of the following combinations: To eliminate text before a given character, type the character preceded by an asterisk (*char). To remove text after a certain character, type the character followed by an asterisk (char*).

How do you delete a string after a certain character?

The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.

How do you delete certain elements from a string?

You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.

How do I cut a string after a specific character in C #?

Solution 1. string str = "this is a #string"; string ext = str. Substring(0, str. LastIndexOf("#") + 1);


2 Answers

For example, you could do:

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

or

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

(and add relevant error handling)

like image 111
assylias Avatar answered Sep 20 '22 06:09

assylias


The apache commons StringUtils provide a substringBefore method

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

like image 22
roemer Avatar answered Sep 18 '22 06:09

roemer