Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to Split the string accordingly

I know this question would have been asked infinite number of times, but I'm kinda stuck. I have a string something like

"Doc1;Doc2;Doc3;12"

it can be something like

"Doc1;Doc2;Doc3;Doc4;Doc5;56"

Its like few pieces of strings separated by semicolon, followed by a number or id.

I need to extract the number/id and the strings separately. To be exact, I can have 2 strings: one having "Doc1;Doc2;Doc3" or "Doc1;Doc2;Doc3;Doc4" and the other having just the number/id as "12" or "34" or "45" etc. And yeah I am using C# 3.5

I understand its a pretty easy and witty question, but this guy is stuck. Assistance required from experts.

Regards Anurag

like image 361
Anurag Avatar asked Jul 18 '13 12:07

Anurag


People also ask

How to split string in c programming?

In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.

How do you split a string but keep the delimiters?

Summary: To split a string and keep the delimiters/separators you can use one of the following methods: Use a regex module and the split() method along with \W special character. Use a regex module and the split() method along with a negative character set [^a-zA-Z0-9] .


2 Answers

string.LastIndexOf and string.Substring are the keys to what you're trying to do.

var str = "Doc1;Doc2;Doc3;12";
var ind = str.LastIndexOf(';');
var str1 = str.Substring(0, ind);
var str2 = str.Substring(ind+1);
like image 194
Tim S. Avatar answered Sep 26 '22 13:09

Tim S.


One way:

string[] tokens = str.Split(';');
var docs = tokens.Where(s => s.StartsWith("Doc", StringComparison.OrdinalIgnoreCase));
var numbers = tokens.Where(s => s.All(Char.IsDigit));
like image 26
Tim Schmelter Avatar answered Sep 24 '22 13:09

Tim Schmelter