Reputation: 474
i have a list that contains : {"something1","something2","somefoo","bar"}
I created a foreach
loop to check for each string.
string input = "thing";
foreach(string word in list) //list = {"something1","something2","somefoo","bar"}
{
if (word.StartContains(input))
return;
}
So as you can see i want to check if my input
string contains in the string in the list.
The result i want is i don't want to get returned in this code.
What StartContains
have to do ??
This method needs to check if the first letters are equal to the input,
Not the entire word like what Contains()
do.
I just have no idea to how to create this...
Thanks,
Upvotes: 0
Views: 516
Reputation: 869
You could use String.StartsWith
Determines whether the beginning of this string instance matches the specified string.
Upvotes: 3
Reputation: 5093
As others have already pointed out, String.StartsWith() is what you are looking for.
But you could also create your own ExtensionMethod for that
public static bool StartsWith(this string baseString, string stringToFind, int lettersToMatch)
{
for(int i = 0; i < lettersToMatch; i++)
{
if(baseString[i] != stringToFind[i])
{
return false;
}
}
return true;
}
You then can call it like this:
bool startsWithMyName = "mynameisfelix".StartsWith("mynameisthomas", 8); // true
startsWithMyName = "mynameisfelix".StartsWith("mynameisthomas", 10); // false
So you could simply ajust the amount of letters you want to match.
Upvotes: 0
Reputation: 1335
Use
String.StartsWith("string")
In your example.
string input = "thing";
foreach(string word in list) //list = {"something1","something2","somefoo","bar"}
{
if (word.StartsWith(input))
{
// TODO: Do Something with the word here.
}
}
Here is a running sample to show off how it works. https://dotnetfiddle.net/mNVK1u
Upvotes: 1
Reputation: 977
Check this
var list = new List<string>();
list.Add("something1");
list.Add("domething1");
list.Add("romething1");
list.Add("yomething1");
string input = "thing";
char[] inputchars = input.ToCharArray();
foreach (string word in list) //list = {"something1","something2","somefoo","bar"}
{
char[] characters = word.ToCharArray();
if (inputchars[0] == characters[0])
list.Remove(word);
}
return list;
Upvotes: 0
Reputation: 2890
The below will create you a list of all entries that match your input.
var input = "som";
var strings = new List<string>()
{"something1","something2","somefoo","bar"};
var stringsThatMatch = strings.Where(item => item.StartsWith(input)).ToList();
Upvotes: 1