-2

I'm trying to split a string up until I get to a certain character. Example:

string test = "Hello(30)";

And I would like the outcome to be: "Hello" Another example:

string test = "Test(50)";

and the outcome: "Test"

How would I go about this? Thanks.

  • 1
    Is Regex an option for you? – James Whyte Jun 08 '18 at 01:02
  • 2
    Why you want the result to be `Hello`? Because you found an `o`? A `(`? Something else? It would be awesome if you could provide a [mcve] with 16 sample inputs and expected results based on those inputs. – mjwills Jun 08 '18 at 01:04
  • 1
    Do you want to split or just get everything from start until that character (excluded)? Split and trim are two different things, and you used both tags. – Andrew Jun 08 '18 at 01:04
  • It looks like they want to split the string at the open parenthesis from the second test case. Maybe they don't need to be fancy with their delimiters? – James Whyte Jun 08 '18 at 01:08
  • `"Hello(30)".Split('(').FirstOrDefault()` – mjwills Jun 08 '18 at 02:38

3 Answers3

2

You want to use the IndexOf function, it returns the first position a character has in a string:

string s = test.Substring(0,test.IndexOf("("));
N.D.C.
  • 1,601
  • 10
  • 13
  • Although this answer is correct in the sense it will return what is needed to split the string from a point, the person that posted the question needs to be more clear in exactly how they need their string chopped up before we can start making worthwhile answers. – James Whyte Jun 08 '18 at 01:06
  • 1
    It looks like the question bloke posted another test case in which the open parenthesis is the required point of splitting. I'm upvoting this answer with the new bounds. :) – James Whyte Jun 08 '18 at 01:09
  • What if there is no `(` in the original string? – mjwills Jun 08 '18 at 02:37
1

Nick posted a straightforward answer with a substring, but if you want something that can string match a lot more complex stuff, look no further than Regex. I suggest you look into how you'd use it in your own time if you aren't familiar, but here's an implementation for your code.

You need to state that you want to include Regex by typing using System.Text.RegularExpressions; at the top of your file.

string test = "Hello(30)";
string match = Regex.Match(test, @"[^(]*").ToString();
//[^(]* == Exclude all after point in search.
//match == "Hello"

Regex can be a mess to read but there's lots of documentation out there if you need to learn more. Just do a search for it online and you'll find what you're looking for.

Refer to this stack overflow comment for the implementation I used.

James Whyte
  • 788
  • 3
  • 14
0
string test = "Test(50)";
string outcome = !test.Contains("(") ? test : test.Substring(0, test.IndexOf("("));
Sasino
  • 134
  • 2
  • 11
  • Please extend your answer with further information and explanations, so it is not just an unexplained block of code. – PhilMasteG Oct 29 '21 at 10:37