I've a filename:
NewReport-20140423_17255375-BSIQ-2wd28830-841c-4d30-95fd-a57a7aege412.zip
How can i split the above filename to 4 string groups.
NewReport
20140423_17255375
BSIQ
2wd28830-841c-4d30-95fd-a57a7aege412.zip
I tried:
string[] strFileTokens = filename.Split(new char[]{'-'} , StringSplitOptions.None);
but i'm not getting the above required four strings
You can specify the maximum number of substrings to return:
This will avoid splitting
2wd28830-841c-4d30-95fd-a57a7aege412.zip
into additional "pieces".(Also, you can drop
StringSplitOptions.None
since that's the default.)Internally, it creates an array of substrings inside a loop, and it only loops the number of times you specify (or the maximum number of delimiters available in your string, whichever is less).
The variable
numActualReplaces
is the minimum of either the count you specify, or the number of actual delimiters present in your string. (That way, if you specify a larger number like 30, but you only have 7 hyphens in the string, you won't get an exception. Actually, when you don't specify a number at all, it's actually usingInt32.MaxValue
without you even realizing it.)You updated your question to say you're using Silverlight, which doesn't have he overloads with
Count
. That's really annoying, because under the hood thestring
class still supports it. They just didn't provide a way to pass in your own value. It uses a hard-codedint.MaxValue
.You could create your own method to bring back the desired functionality. I haven't tested this extension method out for all edge-cases, but it does work with your string.
Make sure it's somewhere accessible to your UserControl, then call it like this:
Since you're using silverlight as shown in your follow up question which doesn't have this overload i show a different approach. You could use LINQ's
Skip
,Take
+string.Join
to get onestring
:Your sample string:
An array with all parts:
Result:
You can use the
Regex.Split
method which offers an overload that takes the count param.It works if you call the overload of
Split
that takes acount
parameter:Obviously you are getting more parts because the last part of your file also contains "-".
An easy way to solve it is to join the remaining parts like this: