user13143185
user13143185

Reputation:

check if a string contains letters from another string

I'm working on a "Create name function". The new name that should be created can't be the same name that already exists. I have a string usernames; that contains all the already existing names like that: Tom bob Harry... and then i have an input field where you can write the new name. string newName = inputField.text

I want to do an if statement that looks if the newName cointains a name from the string usernames. I have already tried this:

if (usernames.Contains(NewName)) //if the newName not already exists

But here was the problem that every newName don't contained the usernames even if it did. I've searched for hours but i'm pretty new to this and couldn't find a good answer. I'm thankful for any help! :)

Upvotes: 0

Views: 218

Answers (2)

Rick Davin
Rick Davin

Reputation: 1041

There is an inherent flaw in having all the names be shoved into one large string. The problem is that Contains could return true when you don't want it. What if usernames already contains "Robert" and the new name to be checked is "Rob"? Now Rob can't enter his name because it conflicts with Robert.

Another example: if you perform a case-insensitive check, then "Liz" or "Beth" would return true if usernames already contains "Elizabeth".

The better design would be to have a collection of individual names. While this could be List<string>, I think a Hashset<string> is a better fit for you needs. If you want searches to be case sensitive, that is "bob" and "Bob" are 2 different names, then you do nothing special:

Hashset<string> usernames = new Hashset<string>();

But if you do want names to be case-insensitive, then you can declare your hash set accordingly:

Hashset<string> usernames = new Hashset<string>(StringComparer.OrdinalIgnoreCase);

The Hashset also has a Contains method but its optimized for fast lookups. For more about Hashset see this link.

UPDATED WITH USINGS

The OP said he could not use Hashset. This is a beginning learner stumbling block. We've all tripped over it when we first started out. To use certain objects, you would either need to fully qualify them, which makes your code look ugly, or else add the appropriate using before your namespace.

  • Hashset<T> is from System.Collections.Generic

  • StringComparer class is from System.

You could use System.Collections.Generic.Hashset<string> but that does seem a bit wordy and ugly. Instead, add these statements before your namespace:

using System;
using System.Collections.Generic;

And Hashset and StringComparer should work fine.

For more on StringComparer, see this link.

Upvotes: 1

KMarron
KMarron

Reputation: 513

I'm not sure I understand what you're really willing to do but I think that IndexOf should do the trick : if(usernames.IndexOf(newName)>0) then newName already exists in usernames.

Or, as you're trying : if(usernames.Contains(newName))

Upvotes: 0

Related Questions