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.
Related
I am currently trying to use Codecademy to learn how to use C# yet the last 'test' for the very second lesson asks us to convert a string to a list. I looked at a forum and it said you had to use loops which was not taught in the course yet, yet I wanted to use a loop anyway, how could I create the list with the for loop which possibly needs fixing? (And maybe help to check whether or not the other code is correct as it asks to convert bool to string and a random data type to another which I chose byte for.) Thanks.
bool pick = true;
byte number = 5;
string myTest = "Ping Pong";
Console.WriteLine(Convert.ToString(pick));
Console.WriteLine(Convert.ToInt32(number));
for ((char(myTest));)
{
Console.WriteLine(i);
}
You use string.ToCharArray to convert the string into an array of characters.
However you don't need to do that just to iterate over it, string implements IEnumerable<char>, so you can iterate over it directly.
Also for ((char(myTest));) makes absolutely no sense.
An string is already a character array and because System.String implements IEnumerable<char> you can just loop it:
/*
References you need:
using System;
using System.Collections.Generic;
using System.Linq;
*/
string myTest = "Ping Pong";
//looping a string
foreach (char character in myTest)
{
Console.WriteLine(character);
}
//Explicit converting a string to list of chars
var listChars = new List<char>();
listChars = myTest.ToList();
foreach (char character in listChars)
{
Console.WriteLine(character);
}
How do I check a string to make sure it contains numbers, letters, or space only?
In C# this is simple:
private bool HasSpecialChars(string yourString)
{
return yourString.Any(ch => ! char.IsLetterOrDigit(ch));
}
The easiest way it to use a regular expression:
Regular Expression for alphanumeric and underscores
Using regular expressions in .net:
http://www.regular-expressions.info/dotnet.html
MSDN Regular Expression
Regex.IsMatch
var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
if(regexItem.IsMatch(YOUR_STRING)){..}
string s = #"$KUH% I*$)OFNlkfn$";
var withoutSpecial = new string(s.Where(c => Char.IsLetterOrDigit(c)
|| Char.IsWhiteSpace(c)).ToArray());
if (s != withoutSpecial)
{
Console.WriteLine("String contains special chars");
}
Try this way.
public static bool hasSpecialChar(string input)
{
string specialChar = #"\|!#$%&/()=?»«#£§€{}.-;'<>_,";
foreach (var item in specialChar)
{
if (input.Contains(item)) return true;
}
return false;
}
String test_string = "tesintg#$234524##";
if (System.Text.RegularExpressions.Regex.IsMatch(test_string, "^[a-zA-Z0-9\x20]+$"))
{
// Good-to-go
}
An example can be found here: http://ideone.com/B1HxA
If the list of acceptable characters is pretty small, you can use a regular expression like this:
Regex.IsMatch(items, "[a-z0-9 ]+", RegexOptions.IgnoreCase);
The regular expression used here looks for any character from a-z and 0-9 including a space (what's inside the square brackets []), that there is one or more of these characters (the + sign--you can use a * for 0 or more). The final option tells the regex parser to ignore case.
This will fail on anything that is not a letter, number, or space. To add more characters to the blessed list, add it inside the square brackets.
Use the regular Expression below in to validate a string to make sure it contains numbers, letters, or space only:
[a-zA-Z0-9 ]
You could do it with a bool. I've been learning recently and found I could do it this way. In this example, I'm checking a user's input to the console:
using System;
using System.Linq;
namespace CheckStringContent
{
class Program
{
static void Main(string[] args)
{
//Get a password to check
Console.WriteLine("Please input a Password: ");
string userPassword = Console.ReadLine();
//Check the string
bool symbolCheck = userPassword.Any(p => !char.IsLetterOrDigit(p));
//Write results to console
Console.WriteLine($"Symbols are present: {symbolCheck}");
}
}
}
This returns 'True' if special chars (symbolCheck) are present in the string, and 'False' if not present.
A great way using C# and Linq here:
public static bool HasSpecialCharacter(this string s)
{
foreach (var c in s)
{
if(!char.IsLetterOrDigit(c))
{
return true;
}
}
return false;
}
And access it like this:
myString.HasSpecialCharacter();
private bool isMatch(string strValue,string specialChars)
{
return specialChars.Where(x => strValue.Contains(x)).Any();
}
Create a method and call it hasSpecialChar with one parameter
and use foreach to check every single character in the textbox, add as many characters as you want in the array, in my case i just used ) and ( to prevent sql injection .
public void hasSpecialChar(string input)
{
char[] specialChar = {'(',')'};
foreach (char item in specialChar)
{
if (input.Contains(item)) MessageBox.Show("it contains");
}
}
in your button click evenement or you click btn double time like that :
private void button1_Click(object sender, EventArgs e)
{
hasSpecialChar(textbox1.Text);
}
While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:
Add the [https://www.nuget.org/packages/Extensions.cs][1] package to your project.
Add "using Extensions;" to the top of your code.
"smith23#".IsAlphaNumeric() will return False whereas "smith23".IsAlphaNumeric() will return True. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden such that "smith 23".IsAlphaNumeric(false) will return False since the space is not considered part of the alphabet.
Every other check in the rest of the code is simply MyString.IsAlphaNumeric().
Based on #prmph's answer, it can be even more simplified (omitting the variable, using overload resolution):
yourString.Any(char.IsLetterOrDigit);
No special characters or empty string except hyphen
^[a-zA-Z0-9-]+$
I am working on a simple windows forms application that the user enters a string with delimiters and I parse the string and only get the variables out of the string.
So for example if the user enters:
2X + 5Y + z^3
I extract the values 2,5 and 3 from the "equation" and simply add them together.
This is how I get the integer values from a string.
int thirdValue
string temp;
temp = Regex.Match(variables[3], #"\d+").Value
thirdValue = int.Parse(temp);
variables is just an array of strings I use to store strings after parsing.
However, I get the following error when I run the application:
Input string was not in a correct format
Why i everyone moaning about this question and marking it down? it's incredibly easy to explain what is happening and the questioner was right to say it as he did. There is nothing wrong whatsoever.
Regex.Match(variables[3], #"\d+").Value
throws a Input string was not in a correct format.. FormatException if the string (here it's variables[3]) doesn't contain any numbers. It also does it if it can't access variables[3] within the memory stack of an Array when running as a service. I SUSPECT THIS IS A BUG The error is that the .Value is empty and the .Match failed.
Now quite honestly this is a feature masquerading as a bug if you ask me, but it's meant to be a design feature. The right way (IMHO) to have done this method would be to return a blank string. But they don't they throw a FormatException. Go figure. It is for this reason you were advised by astef to not even bother with Regex because it throws exceptions and is confusing. But he got marked down too!
The way round it is to use this simple additional method they also made
if (Regex.IsMatch(variables[3], #"\d+")){
temp = Regex.Match(variables[3], #"\d+").Value
}
If this still doesn't work for you you cannot use Regex for this. I have seen in a c# service that this doesn't work and throws incorrect errors. So I had to stop using Regex
I prefer simple and lightweight solutions without Regex:
static class Program
{
static void Main()
{
Console.WriteLine("2X + 65Y + z^3".GetNumbersFromString().Sum());
Console.ReadLine();
}
static IEnumerable<int> GetNumbersFromString(this string input)
{
StringBuilder number = new StringBuilder();
foreach (char ch in input)
{
if (char.IsDigit(ch))
number.Append(ch);
else if (number.Length > 0)
{
yield return int.Parse(number.ToString());
number.Clear();
}
}
yield return int.Parse(number.ToString());
}
}
you can change the string to char array and check if its a digit and count them up.
string temp = textBox1.Text;
char[] arra = temp.ToCharArray();
int total = 0;
foreach (char t in arra)
{
if (char.IsDigit(t))
{
total += int.Parse(t + "");
}
}
textBox1.Text = total.ToString();
This should solve your problem:
string temp;
temp = Regex.Matches(textBox1.Text, #"\d+", RegexOptions.IgnoreCase)[2].Value;
int thirdValue = int.Parse(temp);
I am trying to read a string into an array and I get the error "Cannot implecitly convert type 'string' to 'string[]'.
The error occurs here:
string[] sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
My full if else statement is below:
if (!string.IsNullOrEmpty(result.Tables[0].Rows[0].Field<string>("WebHTML")))
{
string[] sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
NewsContent.Text = sepText[1];
if (!string.IsNullOrEmpty(sepText[0]))
Image1.ImageUrl = sepText[0];
else
Image1.Visible = false;
NewsTitle.Text = String.Format("{3}", Extensions.GetServerName(true), result.Tables[0].Rows[0].Field<int>("News_Item_ID"), result.Tables[0].Rows[0].Field<string>("Title").UrlFormat(), result.Tables[0].Rows[0].Field<string>("Title"));
Hyperlink1.NavigateUrl = String.Format("{0}/news/{1}/{2}.aspx", Extensions.GetServerName(true), result.Tables[0].Rows[0].Field<int>("News_Item_ID"), result.Tables[0].Rows[0].Field<string>("Title").UrlFormat());
}
else
{
Hyperlink1.Visible = false;
Image1.Visible = false;
}
Thank you for your help!
EDIT Code for URL Decode:
public static string UrlDecode(this string str)
{
return System.Web.HttpUtility.UrlDecode(str);
}
result.Tables[0].Rows[0].Field<string>("WebHTML") is going to give you the value of the WebHTML field in the first row in the first table which is a single string rather than a string[].
You may want to show your code for UrlDecode() since it looks like a custom implementation rather than one of the built-in framework versions.
You also declare the UrlDecode method to take a string as a parameter and return a string. Remember, a string is not the same thing as a string array.
It seems that you are trying to put:
result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
which returns a string, into an array of strings.
Simply delare your sepText variable as a string rather than a string array and you should be good to go, e.g.:
string sepText = result.Tables[0].Rows[0].Field<string>("WebHTML").UrlDecode();
Later in your code you will clearly need to read the contents of the string like this:
Image1.ImageUrl =sepText;
Assuming the UrlDecode you are using is the one from here then the result is a string and not a string[] !
UrlDecode returns a string and you are assigning it to an array.
If you want the parts you will have to use the string to create an Url object.
Url url = new Url(result.Tables[0].Rows[0].Field<string>("WebHTML"));
and then get the parts.
See: Get url parts without host
I don't think URLDecode works the way you think it works. All URLDecode does is remove URL encoding from a string. It does not return an array of strings - only the decoded value of the string you gave it.
http://msdn.microsoft.com/en-us/library/system.web.httputility.urldecode.aspx
Example: Your web browser replaces a space with %20. This changes the %20 back to a space.
That's because the result of this line is "string" and you're trying to assign it to an array since UrlDecode do not produce an array. What you probably wanted is to use a method split() to create an array of separators?
I connect to a webservice that gives me a response something like this(This is not the whole string, but you get the idea):
sResponse = "{\"Name\":\" Bod\u00f8\",\"homePage\":\"http:\/\/www.example.com\"}";
As you can see, the "Bod\u00f8" is not as it should be.
Therefor i tried to convert the unicode (\u00f8) to char by doing this with the string:
public string unicodeToChar(string sString)
{
StringBuilder sb = new StringBuilder();
foreach (char chars in sString)
{
if (chars >= 32 && chars <= 255)
{
sb.Append(chars);
}
else
{
// Replacement character
sb.Append((char)chars);
}
}
sString = sb.ToString();
return sString;
}
But it won't work, probably because the string is shown as \u00f8, and not \u00f8.
Now it would not be a problem if \u00f8 was the only unicode i had to convert, but i got many more of the unicodes.
That means that i can't just use the replace function :(
Hope someone can help.
You're basically talking about converting from JSON (JavaScript Object Notation). Try this link--near the bottom you'll see a list of publicly available libraries, including some in C#, that might do what you need.
The excellent Json.NET library has no problems decoding unicode escape sequences:
var sResponse = "{\"Name\":\"Bod\u00f8\",\"homePage\":\"http://www.ex.com\"}";
var obj = (JObject)JsonConvert.DeserializeObject(sResponse);
var name = ((JValue)obj["Name"]).Value;
var homePage = ((JValue)obj["homePage"]).Value;
Debug.Assert(Equals(name, "Bodø"));
Debug.Assert(Equals(homePage, "http://www.ex.com"));
This also allows you to deserialize to real POCO objects, making the code even cleaner (although less dynamic).
var obj = JsonConvert.DeserializeObject<Response>(sResponse);
Debug.Assert(obj2.Name == "Bodø");
Debug.Assert(obj2.HomePage == "http://www.ex.com");
public class Response
{
public string Name { get; set; }
public string HomePage { get; set; }
}
Perhaps you want to try:
string character = Encoding.UTF8.GetString(chars);
sb.Append(character);
I know this question is getting quite old, but I crashed into this problem as of today, while trying to access the Facebook Graph API. I was getting these strange \u00f8 and other variations back.
First I tried a simple replace as the OP also said (with the help from an online table). But I thought "no way!" after adding 2 replaces.
So after looking a little more at the "codes" it suddenly hit me...
The "\u" is a prefix, and the 4 characters after that is a hexadecimal encoded char code! So writing a simple regex to find all \u with 4 alphanumerical characters after, and afterwards converting the last 4 characters to integer and then to a character made the deal.
My source is in VB.NET
Private Function DecodeJsonString(ByVal Input As String) As String
For Each m As System.Text.RegularExpressions.Match In New System.Text.RegularExpressions.Regex("\\u(\w{4})").Matches(Input)
Input = Input.Replace(m.Value, Chr(CInt("&H" & m.Value.Substring(2))))
Next
Return Input
End Function
I also have a C# version here
private string DecodeJsonString(string Input)
{
foreach (System.Text.RegularExpressions.Match m in new System.Text.RegularExpressions.Regex(#"\\u(\w{4})").Matches(Input))
{
Input = Input.Replace(m.Value, ((char)(System.Int32.Parse(m.Value.Substring(2), System.Globalization.NumberStyles.AllowHexSpecifier))).ToString());
}
return Input;
}
I hope it can help someone out... I hate to add libraries when I really only need a few functions from them!