LogicalDesk
LogicalDesk

Reputation: 1297

How to take the first part of string before a specific string occurrence in c#

I have a string that is -

<span style=\"font-weight: 800\">Residence, Effective Date: NA</span> <br />6367 US HIGHWAY 70 EAST<br />LA GRANGE NC 28551 <br />

I want to take the first part of the string before the first occurrence of <br /> and that selected part should be like-

<span style=\"font-weight: 800\">Residence, Effective Date: NA</span>

currently I'm doing like-

string dictVal = "<span style=\"font-weight: 800\">Residence, Effective Date: NA</span> <br />6367 US HIGHWAY 70 EAST<br />LA GRANGE NC 28551 <br />";

                string[] items = dictVal.Split(new char[] { '<' },
                         StringSplitOptions.RemoveEmptyEntries);
                string firstPart = string.Join("<", items.Take(3));

but it's not working.

Upvotes: 1

Views: 51

Answers (2)

mrbear258
mrbear258

Reputation: 56

If you only want to take the first part you can use Regex.Split in the following way:

using System.Text.RegularExpressions;

string dictVal= "< span style =\"font-weight: 800\">Residence, Effective Date: NA</span> <br />6367 US HIGHWAY 70 EAST<br />LA GRANGE NC 28551 <br />";
string first_value = Regex.Split(mystring, "<br />")[0]; //The 0 gets the first portion of the array, in this case it is the desired value

// And if you want to remove any spaces at the beginning and at the end of the string
string trim = first_value.Trim();

Upvotes: 0

DavidG
DavidG

Reputation: 118937

Just use string.Substring and string.IndexOf:

string firstPart = dictVal.Substring(0, dictVal.IndexOf("<br />"))

Upvotes: 2

Related Questions