I am trying to check if value exists in a string array. The below one works but when I tried the next code block, it failed.
bool exixts;
string toCheck= "jupiter";
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains(toCheck))
{
exists = true;
}
How can I check for trim and case sensitivity?
I tried this
bool exixts;
string toCheck= "jupiter ";
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains(toCheck.Trim(),StringComparison.InvariantCultureIgnoreCase)))
{
exists = true;
}
The IEnumerable<string>.Contains(value, comparer) expects a compare class instance, not an enum value.
The library does have some ready made comparers available though:
//if(printer.Contains(toCheck.Trim(),StringComparison.InvariantCultureIgnoreCase)))
if (printer.Contains(toCheck.Trim(), StringComparer.OrdinalIgnoreCase))
Or you can do like this,
bool exists = printer.Any(x=> x == toCheck.Trim());
Hope helps,
Related
I'm tinkering with a very basic password tester. I'm trying to compare the input string with a given string of acceptable characters.
public static bool hasRequiredChar(string input)
{
input = "input";
string requiredChar = "abcde";
foreach (var item in requiredChar)
{
if (input.Contains(item)) return true;
}
return false;
}
If I only use System, I get the error message: "Argument 1: cannot convert from 'char' to 'string'". This refers to the string.Contains() method. Any ideas?
I know there are 1000 ways to write this differently but I don't want to use Regex, Linq or anything other than System.
You're passing to string.Contains a char, when in .NET Framework it instead expects a string. To pass in the argument, simply cast it to a string first.
foreach (var item in requiredChar)
{
if (input.Contains(item.ToString()) return true;
}
There are some other problems with your approach if you're trying to check if the string contains all required characters, but that's aside from your error.
I have the following code:
bool SilentUpdate { get; set;}
....
string temp = "";
SilentUpdate = Convert.ToBoolean(temp ?? "false");
I want to default SilentUpdate to false when temp string is empty. The above code still issue error "String was not recognized as a valid Boolean."
How can I do that?
This is slightly diffrent logic, but this will give you false for any value that does not correctly convert in to a Boolean which is likely what you are really looking for.
string temp = "";
bool result
if(!bool.TryParse(temp, out result))
{
result = false; //This line and the `if` is not actually necessary,
//result will be false if the parse fails.
}
SilentUpdate = result;
Using Convert.ToBoolean the string being parsed must either be a Boolean.TrueString, Boolean.FalseString or null. If it's any other value, then an exception will be thrown, so you must ensure to add a try...catch around the conversion code, example:
string temp = "nope";
SilentUpdate = Convert.ToBoolean(temp); // Exception: "String is not recognized as a valid Boolean"
Using Boolean.TryParse you can alleviate this, as well as get a default value as you're wanting:
string temp = "";
bool res = false;
SilentUpdate = (Boolean.TryParse(temp, out res) ? res : false);
Boolean.TryParse returns true or false if the parse succeeded and if it succeeded the ternary logic returns what was parsed, otherwise it's false.
Hope that can help.
You can use Boolean.TryParse() method as well. It returns bool based on whether the parsing has succeeded or not.
bool flag;
if (Boolean.TryParse(temp, out flag))
The code should be:
SilentUpdate = Convert.ToBoolean(string.IsNullOrEmpty(temp) ? "false" : temp)
You're misusing the ?? operator in your code. It only returns the second operand if the first one is null, not falsy. Empty string is not null and therefore temp ?? "false" returns the empty string, which is not a valid boolean value.
I know that there is lots of questions like this out there.
But I really couldn't find anything that solved my problem.
I want to check if the string contains the specific input number. See the following example:
public Boolean checkString()
{
string input = "2.5.8.12.30";
string intToFind = "3";
if (input.contains(intToFind))
{
return true;
}
else
{
return false;
}
}
This returns true but I want it to return false since the intToFind string is 3 and not 30. So it is the contains() that is the problem.
How do I make it search for 3 only?
You could use String.Split + Contains:
bool contains3 = input.Split('.').Contains("3");
bool anyThree = input.Split('.').Any(str => str == "3");
You may split your input using String.Split('.') into an array. Now use Array.contains to check if the element is within the array
bool contained = input.Split('.').Contains("3");
string[] words = input.Split('.');
if (words.contains("3")){do something...}
You could also use Regex which might be a little overkill.
string str = "2.5.8.12.30";
string strToFind = "3";
bool contains = Regex.Match(str, string.Format(#"\W{0}\W",strToFind)).Success;
string text = "Tag*";
I want check if my string contains * or not.
How do I check this in C#?
You can use String.IndexOf or String.Contains to find if string contains particular string. If you have single character to search you can using String.IndexOf Method (Char)
if(text.IndexOf("*") > -1)
{
}
Return Value Type: System.Int32 The zero-based index position of value
if that string is found, or -1 if it is not. If value is String.Empty,
the return value is 0, MSDN
I dont know how come you dont know this..or how much you googled it but it can be done as follows:
text.Contains("*");
Try Following :
string text = "Tag*";
if(text.Contains("*"))
{
//true
}
else
{
//false
}
You can try the Contains extension to check whether the string contains specific string
string yourText = "abcd*efg";
bool containStar = yourText.Contains("*");
string[] sArray = new string[] { "*" };
string stringToCheck = "Tag*";
bool iscontain = sArray.Any(stringToCheck.Contains);
This seems to be a very odd problem that I cannot figure out for the life of me. I have a path (string) that looks like this:
D:\development\php\bchat\chat\index.php
I need to check if the file in question is a PHP file. I figure the most logical way is to take a substring starting from the . to the end of the string and see if it == .php
So i tried:
bool isphp = (path.Substring(path.LastIndexOf('.')) == ".php") ? true : false;
This always returned false. I thought maybe there was a trailing space at the end screwing me up so i put a TrimEnd() on path before it. But that didn't change anything. So i tried this:
bool isphp = (path.EndsWith(".php") == true) ? true : false;
This also always returns false.
EDIT
I have now also tried this:
bool isphp = (Path.GetExtension(path) == ".php");
But this also returns false.
Use the Path-class. It has a GetExtension() method:
var path = #"D:\development\php\bchat\chat\index.php";
if( Path.GetExtension( path.ToUpperInvariant() ) == ".PHP" )
{}
EDIT: Added check for upper/lower cases
The following code works fine on my machine:
public static void Main()
{
string path = #"D:\development\php\bchat\chat\index.php";
bool isPhp = path.EndsWith(".php");
Console.WriteLine(isPhp);
}
So I would guess there is something else about your string that is causing it not to work. Maybe it is a case thing in which case add StringComparison.InvariantCultureIgnoreCase to your EndsWith call like this.
public static void Main()
{
string path = #"D:\development\php\bchat\chat\index.pHp";
bool isPhp = path.EndsWith(".php", StringComparison.OrdinalIgnoreCase);
Console.WriteLine(isPhp);
}
If that doesn't work put a break point on the comparison line and then type this into the Immediate window:
path[path.Length-1]
You should get this as a result:
112 'p'
If you don't you can tell that your path does not end with a standard p character.
Just a sample for the posted solution:
bool isphp = Path.GetExtension(path)
.Equals(".php", StringComparison.InvariantCultureIgnoreCase);
If it is an existing file you can get the FileInfo object for it and check the extension that way:
FileInfo fi = new FileInfo(#"D:\development\php\bchat\chat\index.php");
if (fi.Exists && fi.Extension == ".php")
{
//Do something
}
Or I suppose you could be a sheep, follow the crowd and use the far better Path.GetExtension method that everyone else has suggested. But ask yourself this question first - do you want to do it the cleanest, fastest and best way, or do you want to assert your individuality and join me down the path of most resistance?
Use Path.GetExtension and compare with the file type you're looking for.
What about Path.GetExtension method?
Make sure that there is no difference in upper/lowercase. You are only testing for lowercase "php".
string ext = Path.GetExtension(path);
bool isPhp = (ext.Equals(".php", StringComparison.InvariantCultureIgnoreCase));
UPDATE:
Check what path.Substring(path.LastIndexOf('.') actually returns - that might point you in the right direction.
private static bool IsPhp(string fileName)
{
return string.Compare(Path.GetExtension(fileName), ".php",
StringComparison.OrdinalIgnoreCase) == 0;
}
I suspect there's something "odd" in your string. I suggest you dump your string out in detail, like this:
foreach (char c in path)
{
Console.WriteLine("'{0}' U+{1:x4}", c, (int) c);
}
That way you'll see any unexpected characters, e.g. unicode char 0s between "real" characters.