Andyww
Andyww

Reputation: 219

splitting string at word - keep the left hand side

I have string, in the middle somewhere (different lengths to left and right) I have this sequence of characters (there is a space to the immediate left and right)

to:

Is there away to split at this point and return the characters on the left i.e. given this string:

Here is some text to: and here is some more text of a different length

The result I would like is:

Here is some text

Upvotes: 1

Views: 604

Answers (3)

user6537189
user6537189

Reputation:

Its easier with string.Split:

Dim FirstSplit as String()
FirstSplit = Name.Split(",")
fname = FirstSplit(0).Trim()

Upvotes: 1

Yotam Salmon
Yotam Salmon

Reputation: 2411

Well, if you know you have that word in there:

String s = "Here is some text to: and here is some more text of a different length"
String result = s.Split(new String[] { "to:" })[0];

You split the text and take the 1st part.

If the substring you chose is not in the string, result will just contain the plain s - no change.

Upvotes: 3

Patrick Hofman
Patrick Hofman

Reputation: 156938

Use IndexOf combined with Substring:

string s = "Here is some text to: and here is some more text of a different length";

int length = s.IndexOf("to:");

if (length > 0)
{
    s = s.Substring(0, length);
}

Upvotes: 3

Related Questions