I should probably rewrite it to remove the syntax error I only just noticed.
"89|43h93::hgjfo::josd.fjfa8j".Split(new string[] { ".", "::", "|" }).Count - 1;
I suppose I probably should have written it out more explicitly.
string text = "89|43h93::hgjfo::josd.fjfa8j";
string[] substringsToCount = new string[] { ".", "::", "|" };
int count = text.Split(substringsToCount).Count - 1;
And what is the minus 1 for at the end of the count?
Is it to take account for array indexes being zero based and not one based?
It’s because Split will return an array containing the entire input text if no matching tokens were found, and the array’s count will therefore always be >= 1.
Why not use the .length method?
Length returns the number of characters in a string, which is not useful here. If you really wanted to use Length, you could do something like this:
int count = Regex.Replace(inputString, @"[^\\.:]", string.Empty).Length;
The ‘@’ preceding the string tells the C# compiler to treat the string literally and proccess the backslashes as backslashes rather than use them to denote special characters (eg., "
" is a newline character). Using ‘^’ negates the characters in the square brackets. I won’t go into detail on the rest, as regular expressions are a topic in itself.
Sorry for all the questions, I’d just rather learn than simply copy and paste.
I applaud this. It’s a rare attitude on these forums.
While we’re on the topic of string manipulation, how can I specify a string, and return everything after the final backslash, (exactly like find and replace “*\” in excel).
I guess you should split by slashes, put it into an array somehow (a little rusty on array manipulation), count the number of items in the array, minus 1 and return that item.
The string object has a LastIndexOf method, I believe. Combined with Substring, it could prove quite useful.
Cheers,
D.