For some reason i cannot get this if statement to work
if (htmlCode.Contains("Sign out") && !htmlCode.Contains("bye bye"))
{
// do stuff...
}
is there any way to get contains and does not contain to work in same if statement?
First of all check the htmlCode, the text could be mixed with some html tags or something like that, also the issue can be with cases, when trying to find some string in the text you should always remember about cases.
You can use .Contains method or .IndexOf, actually the contains method in the Framework is implemented like this:
public bool Contains(string value)
{
return this.IndexOf(value, StringComparison.Ordinal) >= 0;
}
For comparing large strings without knowing the case I would use:
htmlCode.IndexOf("Sign out", StringComparison.InvariantCultureIgnoreCase);
htmlCode.IndexOf("Bye bye", StringComparison.InvariantCultureIgnoreCase);
If you know that response will be small, you can use .ToLower() or .ToUpper()
Try to compare by converting either upper case or lower case.
if (htmlCode.ToUpper().Contains("SIGN OUT") && !htmlCode.ToUpper().Contains("BYE BYE"))
{
// do stuff...
}
You if clause works correctly
It might be not working because of the string case
So i would suggest you do it this way
if (htmlCode.ToUpper().Contains("Sign out".ToUpper()) && !htmlCode.ToUpper().Contains("bye bye".ToUpper()))
Related
This question already has answers here:
How can I check if a string exists in another string
(10 answers)
Closed 4 years ago.
Suppose,i have two strings.NameIs and Nam.Now i can check if one string is as same as the other using :
If (string1 == string2)
But it won't work here as the strings are not the same.But a portion of it is same.What i am trying to achieve is to check if my main string has any portion of the string given...I came across String.StartWith and EndWith methods but there,i need to specify what the string might start or end with but i cannot as the strings can be anything(that's why at the beginning,i said "Suppose").
So my first question is how to achieve this ? I don't want any step=to=step instruction but atleast a little bit of direction :)
However,if i get past that,there's still a drawback and it is the Case-Sensitive issue.I've come across this but i can't seem to figure the required implementation of this in my case because i need to overcome the first issue first.
How should i achieve these ?
For ordinal comparison you can use
str1.Contains(str2);
If you need your comparison to be case-insensitive you can do
str1.IndexOf(str2, StringComparison.OrdinalIgnoreCase) >= 0;
Note that you can hide the latter in an extension method, like
static bool ContainsIgnoreCase(this string #this, string other)
=> #this.IndexOf(other, StringComparison.OrdinalIgnoreCase) >= 0;
Use String.Contains
if (stringValue.ToLower().Contains(anotherString.ToLower())) {
// Do Work //
}
Just remember to check that strings aren't null when doing contains comparing, or you will get an ArgumentNullException..
To check if substring is contained in main string, and to ignore case-sensitivity do this, its a boolean function that takes two string parameters:
public bool DoesStringExistInsideMainString(string mainString, string subString)
{
return mainString.ToLower().Contains(subString.ToLower());
}
Easiest way is this:
a = a?.ToLowerInvariant();
b = b?.ToLowerInvariant();
if(a==null || b==null || a.Contains(b) || b.Contains(a))
{
//do stuff
}
Why null propogates into true? Because if any variable is null it will definitly contains in other variable. The other two specs is just for non-null entries.
I have bunch of usernames in this arraylist and I want to check whether username exists in the arraylist or not but the method always returns false.
public bool check_username(ArrayList userList, string username)
{
for (int i = 0; i < userList.Count; i++)
{
if (userList[i].ToString() == username)
{
return true;
}
}
return false;
}
Consider making your string comparison case insensitive.
username.Equals(userList[i].ToString(), StringComparison.OrdinalIgnoreCase);
Or, assuming all elements of your ArrayList userList are strings, and you're using .NET 3.5 or later, you can simplify this using LINQ:
public bool check_username(ArrayList userList, string username)
{
return userList.Cast<string>()
.Any(s => s.Equals(username, StringComparison.OrdinalIgnoreCase);
}
Without seeing your list or what you are passing we can't know for sure, but it could be a normalization problem.
Bob, bob, BOB, BOb etc... are not the same when comparing strings.
Replace your if statement with this:
if(userList[i].ToString().ToLower() == username.ToLower())
{
return true;
}
There are several reasons I could think of that could cause that function to always return false.
Are you sure that your userList and username will always have the same casing? It would be a good practice to use .ToLower() or .ToUpper() to insure that the casing matches unless you intend for casing to be part of the match.
Are you sure there is no extra whitespace on either string? It is good practice to use .Trim() when you are comparing strings where there may be extra whitespace.
Using the .Equals() method when comparing string is more reliable than the logical operator ==. Occasionally the logical operator produces incorrect results.
Are you positive that you should be getting a true result? Is it possible one string contains a hidden character that you are unaware of? Use the debugger to check the values of the strings to be sure.
i would like to refactor this code. Maybe if possible by using a switch? Or is it the same in terms of performance?
string rawUrl = context.Request.RawUrl ?? string.Empty;
if (rawUrl.Contains("mypage.aspx"))
{
}
if (rawUrl.Contains("mypage2.aspx"))
{
}
etc..
Not directly, since you want a "contains" relation, rather than an exact equality.
However, if you so desire, you could do it indirectly by attempting to parse the page name out of what I assume would be the URL, storing it in a separate String variable, and switching on that String.
For example:
// Get the URL from some external source (wherever you're already getting it from)
String rawUrl = "http://www.example.com/foo/bar.aspx";
// Means of parsing will be dependent on the format in which you expect the URL.
String page = rawUrl.Substring(rawUrl.LastIndexOf("/") + 1);
switch (page) {
case "bar.aspx":
// Do stuff
break;
case "foo.aspx":
// Do stuff
break;
}
And, of course, please take this parsing methodology with a grain of salt; this example was to show you that it is possible, but note that this method of parsing could potentially throw an exception in a number of cases, but I've omitted those checks for the sake of brevity.
Switch Cases must be a constant value. You're best bet there is to use if/else like so:
string rawUrl = context.Request.RawUrl ?? string.Empty;
if (rawUrl.Contains("mypage.aspx"))
{
//code
}
else if (rawUrl.Contains("mypage2.aspx"))
{
//more code
}
If you're concerned about performance (which is good!) then the else is the way to go. While not using an else will have the same functionality, by adding the else, you're telling the code to not process any of the other if conditions. So 10 if statements will result in 10 if conditions being processed not matter what, while 10 if/else statements might result in 10, or it might only result in 1.
EDIT:
Thought about this some, and I noticed you were using the context object. If you really wanted a switch statement, you can do the following:
string page = context.Request.Url.Segments.Last();
switch(page)
{
case "mypage.aspx":
//code
break;
case "mypage2.aspx":
//more code
break;
}
Not for a contains.
Try to isolate page name alone and you can could do it.
switch(pageName)
{
case "mypage.aspx";
break;
case "mypage2.aspx";
break;
}
I think it is better to use a Dictionary.
First, extract the file name from the raw url.
Then, use a Dictionary<string,TValue>.
If the actions to the pages are almost the same, set TValue to the type of the data associated with the pages.
If the actions are very different, set TValue to a delegate type such as Action.
Is there any method in the .NET framework which will return true if a given character is an XML markup character? That is, one of the characters, '"<>_&, and any others that may exist.
I understand I can go for a simple string search also, but was wondering if a built-in method exists which would not rely on manually typing the characters.
You may checkout the following KB article.
I'm not sure the term "XML markup character" (or rather a context-independent function for detecting these) makes much sense, since some of the characters you list only have special meaning depending on the context in which they appear (such as ' and ", which are normal characters if they appear outside of a tag).
Apart from that, you could always write your own such function:
bool IsMarkupCharacter(char ch)
{
switch (ch)
{
case '\'':
case '\"':
case '<':
case '>':
case '&':
return true;
default:
return false;
}
}
Of course you would want to check this against the XML specification to check if it's truly complete. (I didn't include _ from your list, by the way; it is not special to XML in any way, AFAIK.)
You can also use this code
const string XMLCHARS = "'\"\\<>&";
if(XMLCHARS.Contains(c))
{
--
}
You can use extension
public static class CharExtension
{
public static bool IsXmlMarkup(this char charecter)
{
if(charecter == '\'' || charecter == '\"' || e.t.c)
return true;
return false;
}
}
and then just use
char c = '\'';
var res = c.IsXmlMarkup();
In my attempt at dissecting a bit of C# I am afraid I do not understand either the goal or the logic of this bit of code:
if (!string.IsNullOrEmpty(str2) && (Strings.UCase(Strings.Left(str2, 1)) != Strings.Left(str2, 1)))
{
return false;
}
I understand the first part is checking if str2 is "not null", however the second part is coming off a bit flaky. So we UCase the first character of str2, and if it does not equal the first character of str2 (which is NOT "UCase"d), then return "false"?
Maybe I am not missing anything and what I described above is in fact what the code is doing. If this is the case, can we reform this into something else that offers the same result,say for example, check if str2 is uppercase or not? I feel like this is the end goal.
You thoughts?
Yes, you understood the code right.
It looks like something translated from VB using a translation tool, as it's using functions from the VisualBasic namespace. I would rather write it with String methods:
if (!String.IsNullOrEmpty(str2) && str2.Substring(0,1).ToUpper() != str2.SubString(0,1)) {
return false;
}
Or simply getting the first character as a character instead of as a string, and use the IsLower method of the Char class:
if (!string.IsNullOrEmpty(str2) && Char.IsLower(str2[0])) {
return false;
}
My bet is that they are really just testing whether the first character is uppercase. The initial "IsNullOrEmpty" test is just there to make sure that the real test doesn't throw an exception.
The big question: if there is no string value (null or empty) this will not return false. Is that the expected outcome?
Code Objective in English :)
If the non-empty string begins with a lower case character then return false
This is the same, but refactored:
if (!string.IsNullOrEmpty(str2)) {
string s = Strings.Left(str2, 1);
if (Strings.UCase(s) != s) {
return false;
}
}
It is clear that this code tests that the first letter of str2 is or isn't in uppercase when it has any character.
I share the perceptions you have when you say : "I do not understand either the goal or the logic of this bit of code" :) A test that returns only 'false is "fishy" : presumably "something" is waiting for a boolean to be returned, and nothing is returned if the result of this evaluates to 'true.
But if I had to write such a function I'd use the alternative OR logic :
return (! (String.IsNullOrEmpty(testString) || testString.ToUpper()[0] == testString[0]));