I have 3 strings, i would like find matches
http://www.vkeong.com/2011/food-drink/heng-bak-kut-teh-delights-taman-kepong/#comments
http://www.vkeong.com/2009/food-drink/sen-kee-duck-satay-taman-desa-jaya-kepong/
http://www.vkeong.com/2008/food-drink/nasi-lemak-wai-sik-kai-kepong-baru/
for each link above=="nasi-lemak"
{
found!
}
If you're just looking to see if a longer string contains a specific shorter string, use String.Contains.
For your example:
string[] urlStrings = new string[]
{
#"http://www.vkeong.com/2011/food-drink/heng-bak-kut-teh-delights-taman-kepong/#comments"
#"http://www.vkeong.com/2009/food-drink/sen-kee-duck-satay-taman-desa-jaya-kepong"
#"http://www.vkeong.com/2008/food-drink/nasi-lemak-wai-sik-kai-kepong-baru/"
}
foreach(String url in urlStrings)
{
if(url.Contains("nasi-lemak"))
{
//Your code to handle a match here.
}
}
You want the String.IndexOf method.
foreach(string url in url_list)
{
if(url.IndexOf("nasi-lemak") != -1)
{
// Found!
}
}
Surely we also need a LINQ answer :)
var matches = urlStrings.Where(s => s.Contains("nasi-lemak"));
// or if you prefer query form. This is really the same as above
var matches2 = from url in urlStrings
where url.Contains("nasi-lemak")
select url;
// Now you can use matches or matches2 in a foreach loop
foreach (var matchingUrl in matches)
DoStuff(matchingUrl);
Related
I'm trying to search a string to see if it contains any strings from a list,
var s = driver.FindElement(By.Id("list"));
var innerHtml = s.GetAttribute("innerHTML");
innerHtml is the string I want to search for a list of strings provided by me, example
var list = new List<string> { "One", "Two", "Three" };
so if say innerHtml contains "One" output Match: One
You can do this in the following way:
int result = list.IndexOf(innerHTML);
It will return the index of the item with which there is a match, else if not found it would return -1.
If you want a string output, as mentioned in the question, you may do something like:
if (result != -1)
Console.WriteLine(list[result] + " matched.");
else
Console.WriteLine("No match found");
Another simple way to do this is:
string matchedElement = list.Find(x => x.Equals(innerHTML));
This would return the matched element if there is a match, otherwise it would return a null.
See docs for more details.
You can do it with LINQ by applying Contains to innerHtml for each of the items on the list:
var matches = list.Where(item => innerHtml.Contains(item)).ToList();
Variable matches would contain a subset of strings from the list which are matched inside innerHtml.
Note: This approach does not match at word boundaries, which means that you would find a match of "One" when innerHtml contains "Onerous".
foreach(var str in list)
{
if (innerHtml.Contains(str))
{
// match found, do your stuff.
}
}
String.Contains documentation
For those who want to serach Arrray of chars in another list of strings
List WildCard = new() { "", "%", "?" };
List PlateNo = new() { "13eer", "rt4444", "45566" };
if (WildCard.Any(x => PlateNo.Any(y => y.Contains(x))))
Console.WriteLine("Plate has wildchar}");
So I have been asked to remove tour codes that end with the letter G, GE, G=, or Z. The only bad thing is I believe we use this call for a lot of pages and that is the reason I cant alter the database call in the first place so I want to do this specifically for this one person. My code is calling an arrayList that fills with all the tourcodes we have. Is there any way I can remove the tours with the letters above. Here is what I got to work with.
public void LoadTourCodes()
{
ddlTourCode.Items.Clear();
if (ddlTourCode.Visible)
{
ddlTourCode.Items.Add(new ListItem(" ", ""));
ArrayList tourCodes;
tourCodes = EblTipTours.FindTourCodes();
foreach (string tourCode in tourCodes)
{
ddlTourCode.Items.Add(tourCode);
}
}
}
You can do it using LINQ, like this:
var toRemove = new []{"G", "GE", "G=", "Z"};
foreach (string tourCode in tourCodes.Where(code => !toRemove.Any(suffix => code.EndsWith(suffix)))) {
ddlTourCode.Items.Add(tourCode);
}
If you cannot use LINQ because it's a legacy system, you can rewrite the code like this:
string[] toRemove = new string[] {"G", "GE", "G=", "Z"};
foreach (string tourCode in tourCodes) {
bool good = true;
foreach (string suffix in toRemove) {
if (tourCode.EndsWith(suffix)) {
good = false;
break;
}
}
if (!good) continue;
ddlTourCode.Items.Add(tourCode);
}
Basically i have a string list as such:
/forum/
/phpld/
/php/
Now i want to check if any of the url:
http://www.url.com/forum/
contains any values from the string list.
In the above case it should match because /forum/ is in the url.
I was thinking something like this:
foreach (string filter in _filterList)
{
if (PAGEURL.Trim().Contains(filter.Trim()))
{
_parseResultsFinal.Add(PAGEURL);
filteredByURL++;
break;
}
}
But i cannot get the above to be accurate
How would i do this? :)
Try this:
_filterList.Any(filter => PAGEURL.Trim().Contains(filter.Trim()));
You may do PAGEURL = PAGEURL.Trim() before this expression to not run it each time.
String.Contains() is case-sensitive and culture-insensitive, so if there are any case differences that could be the cause of the 'inaccuracy' that you are experiencing.
If you suspect this may be the problem (or even as a viable alternative) you can try this as the 'if' clause:
if (PAGEURL.Trim().IndexOf(filter.Trim(), StringComparison.OrdinalIgnoreCase) >= 0)
I'm not abundantly clear on what you want to do here, it seems as though if a URL contains any of the filters then you want to add the URL to the list.
List<string> parseResultsFinal = new List<string>();
if (_filterList.Any(x => PAGEURL.Contains(x))
{
parseResultsFinal.Add(PAGEURL);
}
Try to use that.
I would try the following:
var trimmedUrl = PageURL.Replace("http://", "");
var parts = trimmedUrl.Split("/");
var filterList = new List<string> { "forum", "phpld", "php" }
var anyContains = parts.Any(o => filterList.contains(o));
I'd change segments filters to simple words (without slashes, trimmed before adding to filter list):
var _filterList = new List<string>()
{
"forum", "phpld", "php"
};
And used regex to search for segments in url (ignore case, optional slash at the end of url)
bool IsSegmentInUrl(string url, string segment)
{
string pattern = String.Format(".*/{0}(/|$)", segment);
return Regex.IsMatch(url, pattern, RegexOptions.IgnoreCase);
}
Usage:
if (_filterList.Any(filter => IsSegmentInUrl(PAGEURL, filter))
{
_parseResultsFinal.Add(PAGEURL);
filteredByURL++;
}
More readable solution - create extensions method
public static bool ContainsSegment(this string url, string segment)
{
string pattern = String.Format("http://.*/{0}(/|$)", segment);
return Regex.IsMatch(url, pattern, RegexOptions.IgnoreCase);
}
Now code looks very self-describing:
if (_filterList.Any(filter => PAGEURL.ContainsSegment(filter))
{
_parseResultsFinal.Add(PAGEURL);
filteredByURL++;
}
I have an ArrayList that import records from a database.
Is there any method to check whether the arrayList contains schname that i want to match to another list which is an api?
List<PrimaryClass> primaryList = new List<PrimaryClass>(e.Result);
PrimaryClass sc = new PrimaryClass();
foreach (string item in str)
{
for (int a = 0; a <= e.Result.Count - 1; a++)
{
string schname = e.Result.ElementAt(a).PrimarySchool;
string tophonour = e.Result.ElementAt(a).TopHonour;
string cca = e.Result.ElementAt(a).Cca;
string topstudent = e.Result.ElementAt(a).TopStudent;
string topaggregate = e.Result.ElementAt(a).TopAggregate;
string topimage = e.Result.ElementAt(a).TopImage;
if (item.Contains(schname))
{
}
}
}
This is what I have come up with so far, kindly correct any errors that I might have committed. Thanks.
How about ArrayList.Contains?
Try this
foreach( string row in arrayList){
if(row.contains(searchString)){
//put your code here.
}
}
Okay, now you've shown that it's actually a List<T>, it should be easy with LINQ:
if (primaryList.Any(x => item.Contains(x.PrimarySchool))
Note that you should really consider using foreach instead of a for loop to iterate over a list, unless you definitely need the index... and if you're dealing with a list, using the indexer is simpler than calling ElementAt.
// check all types
var containsAnyMatch = arrayList.Cast<object>().Any(arg => arg.ToString() == searchText);
// check strings only
var containsStringMatch = arrayList.OfType<string>().Any(arg => arg == searchText);
in my variable:
string selectedObjects;
i have one long value like:
"123;132;213;231;"
i want to get 4 times values as: "123;" , "132;" , "213;" and "231;".
i tryed with foreach as:
public ActionResult ShowHistory(string selectedObjects)
{
foreach (string item in selectedObjects)
{
item = selectedObjects.Split(';');
}
but it doesnt work. how can i do that?
The flow is incorrect. Split returnes an array through which you should than iterate, using foreach if that's your choice. So:
foreach (string item in selectedObjects.Split(';'))
{
// do whatever you want with the items
}
You can use a regular expression:
foreach (Match m in Regex.Matches("123;132;213;231;", #"\d+;"))
string value = m.Value; //Do something worthwhile with the value.
All of the other answers are wrong or overkill - unless I'm missing something.
public ActionResult ShowHistory(string selectedObjects)
{
foreach (string tempItem in selectedObjects.Split(new []{';'}, StringSplitOptions.RemoveEmptyEntries))
{
string item = tempItem + ";"; // Add back on the ; character
}
// .. do something
The RemoveEmptyEntries is required, otherwise, you'll get an empty string at the end (because your input string ends with ";"). Also, string.Split does not preserve the separator char, so you need to add it back in if you want it (hence the tempItem).
Split returns an array of string.
string selectedObjects = ...;
foreach (string item in selectedObjects.Split(';'))
{
// do work
}
foreach(string item in selectedObjects.Split(new [] {';'},
StringSplitOptions.RemoveEmptyEntries)
.Select( x=> x+";"))
{
//process item
}
Split method returns array of string, try somehting like this
string selectedObjects = "123;132;213;231;";
string[] s = selectedObjects.Split(';');
foreach (string item in s )
{
Console.Writeline(item.ToString());
}
You need to append the semi-colon again after splitting.
public ActionResult ShowHistory(string selectedObjects)
{
var items = selectedObjects.Split(';')
.Where(i => !string.IsNullOrEmpty(i))
.Select(i => i + ";");
...
}
Or (if you can guarantee that exact format)
public ActionResult ShowHistory(string selectedObjects)
{
var items = selectedObjects.TrimEnd(';')
.Split(';')
.Select(i => i + ";");
...
}