Reputation: 3530
I've got a string like so
Jamie(123)
And I'm trying to just show Jamie
without the brackets etc
All the names are different lengths so I was wondering if there was a simple way of replacing everything from the first bracket onwards?
Some others are displayed like this
Tom(Test(123))
Jack ((4u72))
I've got a simple replace of the bracket at the moment like this
mystring.Replace("(", "").Replace(")","")
Any help would be appreciated
Thanks
Upvotes: 1
Views: 754
Reputation: 21137
String.Remove(Int32)
will do what you need:
Deletes all the characters from this string beginning at a
specified position and continuing through the last position.
You will also have to .Trim()
as well given the data with padding:
mystring = mystring.Remove(mystring.IndexOf("("C))).Trim()
Upvotes: 0
Reputation: 1376
VB.NET
mystring.Substring(0, mystring.IndexOf("("C)).Trim()
C#
mystring.Substring(0, mystring.IndexOf('(')).Trim();
Upvotes: 1
Reputation: 2849
aneal's will work. The alternative I generally use because it's a bit more flexible is .substring.
string newstring = oldstring.substring(0,oldstring.indexof("("));
If you aren't sure that oldstring will have a "(" you will have to do the test first just as aneal shows in their answer.
Upvotes: 0
Reputation: 4002
One logic; get the index of the (
and you can trim the later part from that position.
public static string Remove(string value)
{
int pos = value.IndexOf("(");
if (pos >= 0)
{
return value.Remove(pos, remove.Length);
}
return value;
}
Upvotes: 0