Reputation: 151
I have a random string and need to know the number of non-letter / non-number characters at the end of it.
For example:
"Some text."
should result in 1
"More text 123 !.?"
should result in 4 (blanks included)
"Even more text 123"
should result in 0
How can I do that?
Upvotes: 2
Views: 175
Reputation: 109537
The problem with using Linq is that Enumerable.Reverse()
makes a copy of the string as a char array and iterates backwards through it, which is not efficient. That might not matter at all to you, but a much more efficient approach is to just loop backwards over the string's characters like so:
string test = "the string to test !*&*& ";
int i;
for (i = test.Length - 1; i >= 0 && !char.IsLetterOrDigit(test[i]); --i)
;
int n = test.Length - i - 1; // n is the count of non-letter/non-digit chars
If you wanted it as a method to call:
public static int CountNonLetterDigitCharsAtEnd(string input)
{
int i;
for (i = input.Length - 1; i >= 0 && !char.IsLetterOrDigit(input[i]); --i)
;
return input.Length - i - 1;
}
Upvotes: 1
Reputation: 1532
It's easy with LINQ:
using System.Linq;
This function also handles null strings and returns -1 for them.
public static int CountNonLettersAtEnd(string input)
=> input?.Reverse().TakeWhile(c => !char.IsLetterOrDigit(c)).Count() ?? -1;
Upvotes: 0
Reputation: 186668
You can try Linq:
string source = "More text 123 !.?";
int result = source
.Reverse()
.TakeWhile(c => !char.IsLetterOrDigit(c))
.Count();
Demo:
string[] tests = new string[] {
"Some text.",
"More text 123 !.?",
"Even more text 123"
};
string demo = string.Join(Environment.NewLine, tests
.Select(s => $"{s,-30} : {s.Reverse().TakeWhile(c => !char.IsLetterOrDigit(c)).Count()}"));
Console.Write(demo);
Outcome:
Some text. : 1
More text 123 !.? : 4
Even more text 123 : 0
Upvotes: 6
Reputation: 11841
You could iterate backwards through the string and use Char.IsLetterOrDigit to determine if it's non-alphanumeric. When you find a letter or digit then stop and return the count.
Upvotes: 0