Check if a String is alphanumeric in Swift - string

In Swift, how can I check if a String is alphanumeric, ie, if it contains only one or more alphanumeric characters [a-zA-Z0-9], excluding letters with diacritics, eg, é.

extension String {
var isAlphanumeric: Bool {
return !isEmpty && range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil
}
}
"".isAlphanumeric // false
"abc".isAlphanumeric // true
"123".isAlphanumeric // true
"ABC123".isAlphanumeric // true
"iOS 9".isAlphanumeric // false

A modern Swift 3 and 4 solution
extension String {
func isAlphanumeric() -> Bool {
return self.rangeOfCharacter(from: CharacterSet.alphanumerics.inverted) == nil && self != ""
}
func isAlphanumeric(ignoreDiacritics: Bool = false) -> Bool {
if ignoreDiacritics {
return self.range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil && self != ""
}
else {
return self.isAlphanumeric()
}
}
}
Usage:
"".isAlphanumeric() == false
"Hello".isAlphanumeric() == true
"Hello 2".isAlphanumeric() == false
"Hello3".isAlphanumeric() == true
"Français".isAlphanumeric() == true
"Français".isAlphanumeric(ignoreDiacritics: true) == false
This works with languages other than English, allowing diacritic characters like è and á, etc. If you'd like to ignore these, use the flag "ignoreDiacritics: true".

I felt the accepted answer using regex was concrete but a rather heavy solution. You could check it this way also in Swift 3.0:
if yourString.rangeOfCharacter(from: CharacterSet.alphanumerics.inverted) != nil {
return "Username can only contain numbers or digits"
}

extension String {
/// Allows only `a-zA-Z0-9`
public var isAlphanumeric: Bool {
guard !isEmpty else {
return false
}
let allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
let characterSet = CharacterSet(charactersIn: allowed)
guard rangeOfCharacter(from: characterSet.inverted) == nil else {
return false
}
return true
}
}
XCTAssertFalse("".isAlphanumeric)
XCTAssertFalse("climate change".isAlphanumeric)
XCTAssertFalse("Poüet".isAlphanumeric)
XCTAssertTrue("Hawking2018".isAlphanumeric)

The problem with the CharacterSet.alphanumerics CharacterSet is that it is more permissive than [a-zA-Z0-9]. It contains letters with diacritics, Eastern Arabic numerals, etc.
assert(["e", "E", "3"].allSatisfy({ CharacterSet.alphanumerics.contains($0) }))
assert(["ê", "É", "٣"].allSatisfy({ CharacterSet.alphanumerics.contains($0) }))
You can build your own CharacterSet using only the specific 62 "alphanumeric" characters:
extension CharacterSet {
static var alphanumeric62: CharacterSet {
return lowercase26.union(uppercase26).union(digits10)
}
static var lowercase26: CharacterSet { CharacterSet(charactersIn: "a"..."z") }
static var uppercase26: CharacterSet { CharacterSet(charactersIn: "A"..."Z") }
static var digits10: CharacterSet { CharacterSet(charactersIn: "0"..."9") }
}
assert(["e", "E", "3"].allSatisfy({ CharacterSet.alphanumeric62.contains($0) }))
assert(["ê", "É", "٣"].allSatisfy({ CharacterSet.alphanumeric62.contains($0) == false }))
Then test your string against the inverse of that CharacterSet:
guard "string".rangeOfCharacter(from: CharacterSet.alphanumeric62.inverted) == nil else {
fatalError()
}

This regex used to check that string contains atleast 1 alphabet + atleast 1 digit alongwith 8 characters.
"^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$"

extension String {
var isAlphaNumeric: Bool {
let hasLetters = rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil
let hasNumbers = rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil
let comps = components(separatedBy: .alphanumerics)
return comps.joined(separator: "").count == 0 && hasLetters && hasNumbers
}
}

Here's a succinct approach:
extension String {
var isAlphanumeric: Bool {
allSatisfy { $0.isLetter || $0.isNumber }
}
}

Related

How to check if string contains both uppercase and lowercase characters

I need to validate password entered by user and check if the password contains at least one uppercase and one lowercase char in Dart.
I wrote this String extension:
extension StringValidators on String {
bool containsUppercase() {
// What code should be here?
}
bool containsLowercase() {
// What code should be here?
}
}
And use it like this:
final text = passwordTextController.text;
final isValid = text.containsUppercase() && text.containsLowercase();
Is there any regexp for this purpose? Or it should be plain algorithm? Please help me to find out the elegant way. Thanks!
Minimum 1 Upper case,
Minimum 1 lowercase,
Minimum 1 Numeric Number,
Minimum 1 Special Character,
Common Allow Character ( ! # # $ & * ~ )
bool validateStructure(String value){
String pattern = r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!##\$&*~]).{8,}$';
RegExp regExp = new RegExp(pattern);
return regExp.hasMatch(value);
}
extension StringValidators on String {
bool get containsUppercase => contains(RegExp(r'[A-Z]'));
bool get containsLowercase => contains(RegExp(r'[a-z]'));
}
For only minimum 1 upper and minimum 1 Lower only, you could use this RegEx:
RegExp regEx = new RegExp(r"(?=.*[a-z])(?=.*[A-Z])\w+");
String a = "aBc";
String b = "abc";
String c = "ABC";
print("a => " + regEx.hasMatch(a).toString());
print("b => " + regEx.hasMatch(b).toString());
print("c => " + regEx.hasMatch(c).toString());
Expected Result:
I/flutter (10220): a => true
I/flutter (10220): b => false
I/flutter (10220): c => false
Reusable
extension StringValidators on String {
meetsPasswordRequirements() {
RegExp regEx = new RegExp(r"(?=.*[a-z])(?=.*[A-Z])\w+");
return regEx.hasMatch(this);
}
}
Use
final isValid = text.meetsPasswordRequirements();
void main() {
solve("coDE");
}
String solve(String s) {
// your code here
List _a = s.split("");
String _b = "";
List _x = [];
List _y = [];
for(var i in _a){
if(i.toString() == i.toString().toUpperCase()){
_x.add(i);
}else{
_y.add(i);
}
}
if(_x.length == _y.length){
_b = _a.join().toLowerCase();
}else if(_x.length > _y.length){
_b = _a.join().toUpperCase();
}else if(_x.length < _y.length){
_b = _a.join().toLowerCase();
}
return "$_b";
}
OR
String solve2(String str) {
return RegExp(r'[A-Z]').allMatches(str).length >
RegExp(r'[a-z]').allMatches(str).length
? str.toUpperCase()
: str.toLowerCase();
}

How to check if a string is all upper or lower case in Go?

What is an easy way in Golang to check if all characters in a string are upper case or lower case?
Also, how to handle a case where the string has punctuation?
See these examples:
package main
import (
"fmt"
"unicode"
)
func main() {
s := "UPPERCASE"
fmt.Println(s.IsUpper()) // Should print true
s = "lowercase"
fmt.Println(s.IsUpper()) // Should print false
s = "lowercase"
fmt.Println(s.IsLower()) // Should print true
s = "I'M YELLING AT YOU!"
fmt.Println(s.IsUpper()) // Should print true
}
Note: s.IsUpper() and s.IsLower() doesn't really exist, but would be nice to find an equivalent.
You can of course compare the upper and lower cased strings in their entirety, or you can short-circuit the comparisons on the first failure, which would be more efficient when comparing long strings.
func IsUpper(s string) bool {
for _, r := range s {
if !unicode.IsUpper(r) && unicode.IsLetter(r) {
return false
}
}
return true
}
func IsLower(s string) bool {
for _, r := range s {
if !unicode.IsLower(r) && unicode.IsLetter(r) {
return false
}
}
return true
}
One solution is to use strings.ToUpper()/ToLower() and compare with the original string. This works for the punctuation case as well.
Here's the solution:
package main
import (
"fmt"
"strings"
)
func main() {
s := "UPPERCASE"
fmt.Println(strings.ToUpper(s) == s)
s = "lowercase"
fmt.Println(strings.ToUpper(s) == s)
s = "lowercase"
fmt.Println(strings.ToLower(s) == s)
s = "I'M YELLING AT YOU!"
fmt.Println(strings.ToUpper(s) == s)
}
A unicode.{IsUpper, Lower} and B strings.{ToUpper, Lower} both good
For the data composed of single bytes, A will be better than B
If the data byte is unsure then B is better than A: for example 中文a1
package main
import (
"strings"
"testing"
"unicode"
)
func IsUpperU(s string) bool {
for _, r := range s {
if !unicode.IsUpper(r) && unicode.IsLetter(r) {
return false
}
}
return true
}
func IsUpper(s string) bool {
return strings.ToUpper(s) == s
}
func IsLowerU(s string) bool {
for _, r := range s {
if !unicode.IsLower(r) && unicode.IsLetter(r) {
return false
}
}
return true
}
func IsLower(s string) bool {
return strings.ToLower(s) == s
}
func TestIsUpper(t *testing.T) {
for _, d := range []struct {
actual bool
expected bool
}{
{IsUpperU("中文A1"), false}, // be careful!
{IsUpper("中文A1"), true},
{IsUpper("中文a1"), false},
{IsUpperU("中文a1"), false},
} {
if d.actual != d.expected {
t.Fatal()
}
}
}
func TestIsLower(t *testing.T) {
for idx, d := range []struct {
actual bool
expected bool
}{
{IsLowerU("中文a1"), false}, // be careful!
{IsLower("中文a1"), true},
{IsLower("中文A1"), false},
{IsLowerU("中文A1"), false},
} {
if d.actual != d.expected {
t.Fatal(idx)
}
}
}
go playground
No need for unicode (For English letters only):
func IsUpper(s string) bool {
for _, charNumber := range s {
if charNumber > 90 || charNumber < 65 {
return false
}
}
return true
}
func IsLower(s string) bool {
for _, charNumber := range s {
if charNumber > 122 || charNumber < 97 {
return false
}
}
return true
}

How do I check to see if a character is a space character in Swift?

In a program I'm writing, I need to check to see if a character is a space (" "). Currently have this as the conditional but it's not working. Any ideas? Thanks in advance.
for(var k = indexOfCharBeingExamined; k < lineBeingExaminedChars.count; k++){
let charBeingExamined = lineBeingExaminedChars[lineBeingExaminedChars.startIndex.advancedBy(k)];
//operations
if(String(charBeingExamined) == " "){
//more operations
}
}
The code below is how I solved this problem with a functional approach in Swift. I made an extension (two, actually), but you could easily take the guts of the function and use it elsewhere.
extension String {
var isWhitespace: Bool {
guard !isEmpty else { return true }
let whitespaceChars = NSCharacterSet.whitespacesAndNewlines
return self.unicodeScalars
.filter { !whitespaceChars.contains($0) }
.count == 0
}
}
extension Optional where Wrapped == String {
var isNullOrWhitespace: Bool {
return self?.isWhitespace ?? true
}
}
The following code works for me. Note that it's easier to just iterate over the characters in a string using 'for' (second example below):
var s = "X yz"
for var i = 0; i < s.characters.count; i++ {
let x = s[s.startIndex.advancedBy(i)]
print(x)
print(String(x) == " ")
}
for c in s.characters {
print(c)
print(String(c) == " ")
}
String:
let origin = "Some string with\u{00a0}whitespaces" // \u{00a0} is a no-break space
Oneliner:
let result = origin.characters.contains { " \u{00a0}".characters.contains($0) }
Another approach:
let spaces = NSCharacterSet.whitespaceCharacterSet()
let result = origin.utf16.contains { spaces.characterIsMember($0) }
Output:
print(result) // true
Not sure what you want to do with the spaces, because then it could be a bit simpler.
just in your code change " " -> "\u{00A0}"
for(var k = indexOfCharBeingExamined; k < lineBeingExaminedChars.count; k++){
let charBeingExamined = lineBeingExaminedChars[lineBeingExaminedChars.startIndex.advancedBy(k)];
if(String(charBeingExamined) == "\u{00A0}"){
//more operations
}
}
To test just for whitespace:
func hasWhitespace(_ input: String) -> Bool {
let inputCharacterSet = CharacterSet(charactersIn: input)
return !inputCharacterSet.intersection(CharacterSet.whitespaces).isEmpty
}
To test for both whitespace and an empty string:
func hasWhitespace(_ input: String) -> Bool {
let inputCharacterSet = CharacterSet(charactersIn: input)
return !inputCharacterSet.intersection(CharacterSet.whitespaces).isEmpty || inputCharacterSet.isEmpty
}

Checking if string is numeric in dart

I need to find out if a string is numeric in dart. It needs to return true on any valid number type in dart. So far, my solution is
bool isNumeric(String str) {
try{
var value = double.parse(str);
} on FormatException {
return false;
} finally {
return true;
}
}
Is there a native way to do this? If not, is there a better way to do it?
This can be simpliefied a bit
void main(args) {
print(isNumeric(null));
print(isNumeric(''));
print(isNumeric('x'));
print(isNumeric('123x'));
print(isNumeric('123'));
print(isNumeric('+123'));
print(isNumeric('123.456'));
print(isNumeric('1,234.567'));
print(isNumeric('1.234,567'));
print(isNumeric('-123'));
print(isNumeric('INFINITY'));
print(isNumeric(double.INFINITY.toString())); // 'Infinity'
print(isNumeric(double.NAN.toString()));
print(isNumeric('0x123'));
}
bool isNumeric(String s) {
if(s == null) {
return false;
}
return double.parse(s, (e) => null) != null;
}
false // null
false // ''
false // 'x'
false // '123x'
true // '123'
true // '+123'
true // '123.456'
false // '1,234.567'
false // '1.234,567' (would be a valid number in Austria/Germany/...)
true // '-123'
false // 'INFINITY'
true // double.INFINITY.toString()
true // double.NAN.toString()
false // '0x123'
from double.parse DartDoc
* Examples of accepted strings:
*
* "3.14"
* " 3.14 \xA0"
* "0."
* ".0"
* "-1.e3"
* "1234E+7"
* "+.12e-9"
* "-NaN"
This version accepts also hexadecimal numbers
bool isNumeric(String s) {
if(s == null) {
return false;
}
// TODO according to DartDoc num.parse() includes both (double.parse and int.parse)
return double.parse(s, (e) => null) != null ||
int.parse(s, onError: (e) => null) != null;
}
print(int.parse('0xab'));
true
UPDATE
Since {onError(String source)} is deprecated now you can just use tryParse:
bool isNumeric(String s) {
if (s == null) {
return false;
}
return double.tryParse(s) != null;
}
In Dart 2 this method is deprecated
int.parse(s, onError: (e) => null)
instead, use
bool _isNumeric(String str) {
if(str == null) {
return false;
}
return double.tryParse(str) != null;
}
Even shorter. Despite the fact it will works with double as well, using num is more accurately.
isNumeric(string) => num.tryParse(string) != null;
num.tryParse inside:
static num tryParse(String input) {
String source = input.trim();
return int.tryParse(source) ?? double.tryParse(source);
}
for anyone wanting a non native way using regex
RegExp _numeric = RegExp(r'^-?[0-9]+$');
/// check if the string contains only numbers
bool isNumeric(String str) {
return _numeric.hasMatch(str);
}
if (int.tryParse(value) == null) {
return 'Only Number are allowed';
}
Yes, there is a more "sophisticated" way *rsrs*.
extension Numeric on String {
bool get isNumeric => num.tryParse(this) != null ? true : false;
}
main() {
print("1".isNumeric); // true
print("-1".isNumeric); // true
print("2.5".isNumeric); // true
print("-2.5".isNumeric); // true
print("0x14f".isNumeric); // true
print("2,5".isNumeric); // false
print("2a".isNumeric); // false
}
import 'dart:convert';
void main() {
//------------------------allMatches Example---------------------------------
print('Example 1');
//We want to extract ages from the following string:
String str1 = 'Sara is 26 years old. Maria is 18 while Masood is 8.';
//Declaring a RegExp object with a pattern that matches sequences of digits
RegExp reg1 = new RegExp(r'(\d+)');
//Iterating over the matches returned from allMatches
Iterable allMatches = reg1.allMatches(str1);
var matchCount = 0;
allMatches.forEach((match) {
matchCount += 1;
print('Match ${matchCount}: ' + str1.substring(match.start, match.end));
});
//------------------------firstMatch Example---------------------------------
print('\nExample 2');
//We want to find the first sequence of word characters in the following string:
//Note: A word character is any single letter, number or underscore
String str2 = '#%^!_as22 d3*fg%';
//Declaring a RegExp object with a pattern that matches sequences of word
//characters
RegExp reg2 = new RegExp(r'(\w+)');
//Using the firstMatch function to display the first match found
Match firstMatch = reg2.firstMatch(str2) as Match;
print('First match: ${str2.substring(firstMatch.start, firstMatch.end)}');
//--------------------------hasMatch Example---------------------------------
print('\nExample 3');
//We want to check whether a following strings have white space or not
String str3 = 'Achoo!';
String str4 = 'Bless you.';
//Declaring a RegExp object with a pattern that matches whitespaces
RegExp reg3 = new RegExp(r'(\s)');
//Using the hasMatch method to check strings for whitespaces
print(
'The string "' + str3 + '" contains whitespaces: ${reg3.hasMatch(str3)}');
print(
'The string "' + str4 + '" contains whitespaces: ${reg3.hasMatch(str4)}');
//--------------------------stringMatch Example-------------------------------
print('\nExample 4');
//We want to print the first non-digit sequence in the following strings;
String str5 = '121413dog299toy01food';
String str6 = '00Tom1231frog';
//Declaring a RegExp object with a pattern that matches sequence of non-digit
//characters
RegExp reg4 = new RegExp(r'(\D+)');
//Using the stringMatch method to find the first non-digit match:
String? str5Match = reg4.stringMatch(str5);
String? str6Match = reg4.stringMatch(str6);
print('First match for "' + str5 + '": $str5Match');
print('First match for "' + str6 + '": $str6Match');
//--------------------------matchAsPrefix Example-----------------------------
print('\nExample 5');
//We want to check if the following strings start with the word "Hello" or not:
String str7 = 'Greetings, fellow human!';
String str8 = 'Hello! How are you today?';
//Declaring a RegExp object with a pattern that matches the word "Hello"
RegExp reg5 = new RegExp(r'Hello');
//Using the matchAsPrefix method to match "Hello" to the start of the strings
Match? str7Match = reg5.matchAsPrefix(str7);
Match? str8Match = reg5.matchAsPrefix(str8);
print('"' + str7 + '" starts with hello: ${str7Match != null}');
print('"' + str8 + '" starts with hello: ${str8Match != null}');
}
bool isOnlyNumber(String str) {
try{
var value = int.parse(str);
return true;
} on FormatException {
return false;
}
}
Building on Matso Abgaryan's answer and Günter Zöchbauer's updated answer,
I can get a ',' (comma) on my numeric soft keyboard while developing mobile apps in flutter, and double.tryParse() can return Nan as well as null - so checking vs null is not enough if a user can enter a comma on a soft numeric keyboard. If a string is empty, using double.tryParse() will produce null - so that edge case will be caught using this function;
bool _isNumeric(String str) {
if (str == null) {
return false;
}
return double.tryParse(str) is double;
}
Documentation for tryParse()

Easy way to search a string for strings

I'm trying to find the easiest way to search a string for an array of possible strings. I know the easy way to do this for characters is to use myString.IndexOfAny(charArray). But how what if I'd like to search my string for strings and not just characters? Are there any .net tricks or methods that make this easier?
Basically, I'd like to do something like this:
string myName = "rahkim";
string[] names = new string[] {"joe","bob","chris"};
if(myName.IndexOfAny(names) >= 0)
{
//success code//
}
I know there are ways to do this with loops, etc. But I was hoping for something inherent in the framework.
You should define if you want to to find equal strings or search for a matching substring. Both ways are easy pre-LINQ and with LINQ.
string myName = "rahkim";
string[] names = new string[] { "joe", "bob", "chris" };
Equal Strings, LINQ
bool contains = names.Contains(myName);
Equal Strings, Pre-LINQ
bool contains = new List<string>(name).Contains(myName);
Substrings, LINQ
bool contains = names.Any(name => name.Contains(myName));
Substring, Pre-LINQ
bool contains = false;
foreach(string name in names)
if (name.Contains(myName))
contains = true;
If anyone else found this while trying to search for a .Net method like String.IndexOfAny(String[]), this is my solution:
C#
public int IndexOfAny(string test, string[] values)
{
int first = -1;
foreach (string item in values) {
int i = test.IndexOf(item);
if (i >= 0) {
if (first > 0) {
if (i < first) {
first = i;
}
} else {
first = i;
}
}
}
return first;
}
VB
Public Function IndexOfAny(test As String, values As String()) As Integer
Dim first As Integer = -1
For Each item As String In values
Dim i As Integer = test.IndexOf(item)
If i >= 0 Then
If first > 0 Then
If i < first Then
first = i
End If
Else
first = i
End If
End If
Next
Return first
End Function
You can do a LastIndexOfAny(String[]) by just switching the
i < first
to
i > first
You can (also) use the static IndexOf method of the Array class:
bool hasName = Array.IndexOf(names, myName) > -1;
int IndexOfAny(String[] rgs) would indeed be nice but it's nominally an O(n^2) operation. If, in your application, the set of strings rgs is large and always the same, the most efficient approach is to load them into a trie data structure once, and then use the trie repeatedly to search for them within the unknown strings given at runtime.
Here is the relevant code, adapted from a C# trie source I found on the web, attributed to "Kerry D. Wong." In my version, each string in the trie has a "payload" of generic type TValue. To use this trie to simply search for substrings, the payload could always be set to true, as illustrated with simple_trie.
The other thing I changed here is that this trie automatically adapts allow for storage of arbitrary Unicode strings. The array at each node—which characterizes a trie—adjusts its base and length to accomodate the range of Unicode characters which need to be stored at that node. This allows for case-sensitive matching, for example.
The C# 3.0 initialization syntax is handy for this trie, but enabling it requires a dummy implementation of IEnumerable in order to compile. The CLR doesn't seem to call GetEnumerator() and I suggest that you don't try to enumerate with its result either.
using System;
using System.Collections.Generic;
using System.Linq; // only used in Main()
class Program
{
// trie with payload of type <String>
static Trie<String> value_trie = new Trie<String>
{
{ "rabbit", "cute" },
{ "giraffe", "tall" },
{ "ape", "smart" },
{ "hippo", "large" },
};
// degenerate case of a trie without payload
static Trie<bool> simple_trie = new Trie<bool>
{
{ "rabbit", true },
{ "giraffe", true },
{ "ape", true },
{ "hippo", true },
};
static void Main(String[] args)
{
String s = "Once upon a time, a rabbit met an ape in the woods.";
// Retrieve payloads for words in the string.
//
// output:
// cute
// smart
foreach (String word in value_trie.AllSubstringValues(s))
Console.WriteLine(word);
// Simply test a string for any of the words in the trie.
// Note that the Any() operator ensures that the input is no longer
// traversed once a single result is found.
//
// output:
// True
Console.WriteLine(simple_trie.AllSubstringValues(s).Any(e=>e));
s = "Four score and seven years ago.";
// output:
// False
Console.WriteLine(simple_trie.AllSubstringValues(s).Any(e => e));
}
}
class TrieNode<TValue>
{
private TrieNode<TValue>[] nodes = null;
private TValue m_value = default(TValue);
private Char m_base;
public Char Base { get { return m_base; } }
public bool IsEnd { get { return !m_value.Equals(default(TValue)); } }
public TValue Value
{
get { return m_value; }
set { m_value = value; }
}
public IEnumerable<TrieNode<TValue>> Nodes { get { return nodes; } }
public TrieNode<TValue> this[char c]
{
get
{
if (nodes != null && m_base <= c && c < m_base + nodes.Length)
return nodes[c - m_base];
return null;
}
}
public TrieNode<TValue> AddChild(char c)
{
if (nodes == null)
{
m_base = c;
nodes = new TrieNode<TValue>[1];
}
else if (c >= m_base + nodes.Length)
{
Array.Resize(ref nodes, c - m_base + 1);
}
else if (c < m_base)
{
Char c_new = (Char)(m_base - c);
TrieNode<TValue>[] tmp = new TrieNode<TValue>[nodes.Length + c_new];
nodes.CopyTo(tmp, c_new);
m_base = c;
nodes = tmp;
}
TrieNode<TValue> node = nodes[c - m_base];
if (node == null)
{
node = new TrieNode<TValue>();
nodes[c - m_base] = node;
}
return node;
}
};
class Trie<TValue> : System.Collections.IEnumerable
{
private TrieNode<TValue> _root = new TrieNode<TValue>();
// This dummy enables C# 3.0 initialization syntax
public System.Collections.IEnumerator GetEnumerator()
{
return null;
}
public void Add(String s, TValue v)
{
TrieNode<TValue> node = _root;
foreach (Char c in s)
node = node.AddChild(c);
node.Value = v;
}
public bool Contains(String s)
{
TrieNode<TValue> node = _root;
foreach (Char c in s)
{
node = node[c];
if (node == null)
return false;
}
return node.IsEnd;
}
public TValue Find(String s_in)
{
TrieNode<TValue> node = _root;
foreach (Char c in s_in)
{
node = node[c];
if (node == null)
return default(TValue);
}
return node.Value;
}
public IEnumerable<TValue> FindAll(String s_in)
{
TrieNode<TValue> node = _root;
foreach (Char c in s_in)
{
node = node[c];
if (node == null)
break;
if (node.Value != null)
yield return node.Value;
}
}
public IEnumerable<TValue> AllSubstringValues(String s)
{
int i_cur = 0;
while (i_cur < s.Length)
{
TrieNode<TValue> node = _root;
int i = i_cur;
while (i < s.Length)
{
node = node[s[i]];
if (node == null)
break;
if (node.Value != null)
yield return node.Value;
i++;
}
i_cur++;
}
}
};
Here's the right syntax:
if(names.Contains(myName))
{
//success code//
}
if (names.Contains(myName))
{
//success code//
}

Resources