C
C#7mo ago
js

way to check if a string contains only alphabet

I need a line of code to check if a string contains only alphabet characters or whitespaces, what is the best way to do so
4 Replies
MODiX
MODiX7mo ago
arion
REPL Result: Success
var words = "Hello there";
words.All(x => char.IsLetter(x) || char.IsWhiteSpace(x))
var words = "Hello there";
words.All(x => char.IsLetter(x) || char.IsWhiteSpace(x))
Result: bool
True
True
Compile: 392.695ms | Execution: 53.353ms | React with ❌ to remove this embed.
arion
arion7mo ago
If you want it more structured you can extract the predicate
MODiX
MODiX7mo ago
arion
REPL Result: Success
var words = "Hello there";
var predicate = (char c) => char.IsLetter(c) || char.IsWhiteSpace(c);
words.All(predicate)
var words = "Hello there";
var predicate = (char c) => char.IsLetter(c) || char.IsWhiteSpace(c);
words.All(predicate)
Result: bool
True
True
Compile: 422.296ms | Execution: 55.121ms | React with ❌ to remove this embed.
arion
arion7mo ago
Regarding what the best way to do so is, that well, it depends. Is your interpretation of "best" speed? memory usage? how many lines of code? Linq is nice on the lines of code but there are memory implications and it might not be the fastest. You can try to write your own implementation to try to beat System.Linq's .All
Want results from more Discord servers?
Add your server