简体   繁体   中英

String.Split cut separator

Is it possible to use String.Split without cutting separator from string?

For example I have string

convertSource = "http://www.domain.com http://www.domain1.com";

I want to build array and use code below

convertSource.Split(new[] { " http" }, StringSplitOptions.RemoveEmptyEntries)

I get such array

[1] http://www.domain.com
[2] ://www.domain1.com

I would like to keep http, it seems String.Split not only separate string but also cut off separator.

This is screaming for Regular Expressions:

Regex regEx = new Regex(@"((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)");
Match match= regEx.Match("http://www.domain.com http://www.domain1.com");

IList<string> values = new List<string>();
while (match.Success)
{
     values.Add(match.Value);
     match = match.NextMatch();
}
string[] array = Regex.Split(convertSource, @"(?=http://)");

That's because you use " http" as separator.

Try this:

string separator = " ";
convertSource.Split(separator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries)

The Split method works in a way that when it comes to the separator you provide it cuts it off right there and removes the separator from the string also.

From what you are saying you want to do there are other ways to split the string keeping the delimiters and then if you only want to remove leading or trailing spaces from your string then I wouuld suggest that you use .Trim() method: convertSource.Trim()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM