Check for special characters (/*-+_#&$#%) in a string? - c#

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-]+$

Related

Making one line string

I need help I have task in c# to make program that take user input (string).You are given the noises made by different animals that you can hear in the dark, evaluate each noise to determine which animal it belongs to. Lions say 'Grr', Tigers say 'Rawr', Snakes say 'Ssss', and Birds say 'Chirp'.
Input Format:
A string that represent the noises that you hear with a space between them.
Output Format:
A string that includes each animal that you hear with a space after each one. (animals can repeat)
I make this
using System;
using System.Reflection.Metadata;
using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
namespace nekaVjezba
{
class Program
{
static void Main(string[] args)
{
var text = Console.ReadLine();
var matches = Regex.Matches(text, #"\w+[^\s]*\w+|\w");
foreach (Match match in matches)
{
var word = match.Value;
if (word == "Grr")
{
Console.WriteLine("Lion");
}
else if (word == "Rawr")
{
Console.WriteLine("Tiger");
}
else if (word == "Ssss")
{
Console.WriteLine("Snake");
}
else if (word == "Chirp")
{
Console.WriteLine("Bird");
}
}
}
}
}
That is work but my output is
Lion
Lion
Tiger
Snake
but it should be in one line
Lion Lion Tiger Snake
Write instead of Console.WriteLine("...") just Console.Write("..."), so you don't write to a new line, but on the same line. Then add a space after each word that should be output (Console.Write("Tiger ");), as indicated in the following code:
using System;
using System.Reflection.Metadata;
using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
namespace nekaVjezba
{
class Program
{
static void Main(string[] args)
{
var text = Console.ReadLine();
var matches = Regex.Matches(text, #"\w+[^\s]*\w+|\w");
foreach (Match match in matches)
{
var word = match.Value;
if (word == "Grr")
{
Console.WriteLine("Lion ");
}
else if (word == "Rawr")
{
Console.Write("Tiger ");
}
else if (word == "Ssss")
{
Console.Write("Snake ");
}
else if (word == "Chirp")
Console.Write("Bird ");
}
}
}
}
Output now can be : "Lion Lion Tiger Snake"
There are a few ways to improve this but the simplest advice might be to build a single output string, add to it and write it to the console in a single statement, something like this (semi pseudo code):
//Intitialize an output string
var output = "";
foreach(Match match in matches)
//Add to output
If(word== "Grr")
{ outPut += "Lion ";}
...
}
//Then after all results are added to the string, print the string
Console.WriteLine(output)
Though there are many ways to do this. However, here is a succinct solution (to ô̖p̖̝̃̉en̺͔͍͌̍̈́ y̯͇̦͌̍͌oũ̠͍̫̀͡r̜̚ m̠̞͑̍i̭̓ṇ̼̍͘d͈̪͍̑̚͝) using a Dictionary and LINQ.
Since the words are separated by a space, then a simple string.Split would work fine.
var dict = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase)
{
{"Grr", "Lion"},
{"Rawr", "Tiger"},
{"Ssss", "Snake"},
{"Chirp", "Bird"},
};
var animals = Console
.ReadLine()?
.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Select(word => !dict.TryGetValue(word, out var animal) ? "N/A" : animal)
.ToList();
if (animals?.Any() == true)
Console.WriteLine(string.Join(", ", animals));
else
Console.WriteLine("Nothing entered");
Input
grr bob chirp ssss
Output
Lion, N/A, Bird, Snake
Additional Resources
String.Split Method
Returns a string array that contains the substrings in this instance
that are delimited by elements of a specified string or Unicode
character array.
Dictionary<TKey,TValue>(IEqualityComparer)
The IEqualityComparer<T> implementation to use when comparing keys, or
null to use the default EqualityComparer<T> for the type of the key.
Dictionary<TKey,TValue>.TryGetValue(TKey, TValue) Method
Gets the value associated with the specified key.
Enumerable.Select Method
Projects each element of a sequence into a new form.
string.Join
Concatenates the elements of a specified array or the members of a
collection, using the specified separator between each element or
member.
Null-conditional operators ?. and ?[]
Available in C# 6 and later, a null-conditional operator applies a
member access, ?., or element access, ?[], operation to its operand
only if that operand evaluates to non-null; otherwise, it returns null
Language Integrated Query (LINQ)
Language-Integrated Query (LINQ) is the name for a set of technologies
based on the integration of query capabilities directly into the C#
language. Traditionally, queries against data are expressed as simple
strings without type checking at compile time or IntelliSense support.
Furthermore, you have to learn a different query language for each
type of data source: SQL databases, XML documents, various Web
services, and so on. With LINQ, a query is a first-class language
construct, just like classes, methods, events. You write queries
against strongly typed collections of objects by using language
keywords and familiar operators.
Couple things could make this easier to do.
First you don't need a regular expression to parse space delimited input. So unless that's a requirement you can just use String.Split.
Second you can use either a switch statement or a switch expression to match the input tokens. And you can break that out into a separate method as well. Here's an example using a switch expression:
static IEnumerable<string> ToAnimal(IEnumerable<string> sounds)
{
foreach (var sound in sounds)
{
yield return sound switch
{
"Grr" => "Lion",
"Rawr" => "Tiger",
"Ssss" => "Snake",
"Chirp" => "Bird",
_ => throw new ArgumentException("unknown sound")
};
}
}
You can call that using the result from string.Split. Like so:
static void Main(string[] _)
{
string RawInput = "Grr Grr Rawr Ssss";
string[] sounds = RawInput.Split(' ');
foreach (var animal in ToAnimal(sounds))
{
Console.Write(animal);
Console.Write(' ');
}
Console.WriteLine();
}
Obviously you'll want to use Console.ReadLine to get the input string.

How to check if a textbox starts with numeric value

In Windows forms C#, I want to check if a textbox I made starts with a numeric value, then if it does I want to insert the minus (-) sign at the beginning to change the number to negative, I found a way but it's too time wasting, here's my code:
if (richTextBox1.Text.StartsWith("1") || richTextBox1.Text.StartsWith("2") #until richTextBox1.Text.StartsWith("9"))
{
richTextBox1.Text.Insert(0, "-");
}
So I was asking, if there's a shorter way to replace that code?
if (Char.IsNumber(richTextBox1.Text[0]))...
You should also add some checks around it to make sure there's text.
Using regex:
if (Regex.IsMatch(richTextBox1.Text, #"^\d"))
Matches a digit (0-9) at the start of the string.
Or a direct replace:
richTextBox1.Text = Regex.Replace(richTextBox1.Text, #"^\d", "-$&");
Checking if the first character of a text is a number can be done in single line, using Char.IsNumber() function as follows:
if ( Char.IsNumber( stringInput, 0) ) {
// String input begins with a number
}
More information:
https://learn.microsoft.com/en-us/dotnet/api/system.char.isnumber
Many good answer's already here, another alternative is if you want culture support give this a try...
public static bool IsNumber(char character)
{
try
{
int.Parse(character.ToString(), CultureInfo.CurrentCulture);
return true;
}
catch (FormatException) { return false; }
}
You can call it like:
if ( IsNumber(richTextBox1.Text[0]))

words stemmer class c#

I am trying the following stemming class :
static class StemmerSteps
{
public static string stepSufixremover(this string str, string suffex)
{
if (str.EndsWith(suffex))
{
................
}
return str;
}
public static string stepPrefixemover(this string str, string prefix)
{
if (str.StartsWith(prefix)
{
.....................
}
return str;
}
}
this class works with one prefix or suffix. is there any suggestion to allow a list of prefixes or suffixes to go through the class and compare against each (str). your kind action really appreciated.
Instead of creating your own class from scratch (unless this is homework) I would definitive use an existing library. This answer provides an example of code that that implements the Porter Stemming Algorithm:
https://stackoverflow.com/questions/7611455/how-to-perform-stemming-in-c
Put your suffix/prefixes in a collection (like a List<>), and loop through and apply each possible one. This collection would need to be passed into the method.
List<string> suffixes = ...;
for (suffix in suffixes)
if (str.EndsWith(suffix))
str = str.Remove(str.Length - suffix.Length, suffix.Length);
EDIT
Considering your comment:
"just want to look if the string starts-/endswith any of the passed strings"
may be something like this can fit your needs:
public static string stepSufixremover(this string str, IEnumerable<string> suffex)
{
string suf = suffex.Where(x=>str.EndsWith(x)).SingleOrDefault();
if(!string.IsNullOrEmpty(suf))
{
str = str.Remove(str.Length - suf.Length, suf.Length);
}
return str;
}
If you use this like:
"hello".stepone(new string[]{"lo","l"}).Dump();
it produces:
hel
The simplest code would involve regular expressions.
For example, this would identify some English suffixes:
'^(.*?)(ing|ly|ed|ious|ies|ive|es|s|ment)?$'
One problem is that stemming is not as accurate as lemmatization. Lematization would require POS tagging for accuracy. For example, you don't want to add an -ing suffix to dove if it's a noun.
Another problem is that some suffixes also require prefixes. For example, you must add en- to -rich- to add a -ment suffix in en-rich-ment -- unlike a root like -govern- where you can add the suffix without any prefix.

Change Variable back to original value after Regex matching

I just "finished" expanding my Palindrome Tester, made in C#. To allow for phrases I added a simple regex match for all non-alphanumeric characters. At the end of the program it states " is(n't) a palindrome." But now with the regex it prints the no spaces/punctuation version of it.
I would like to be able to print the original user input. How do I do that?
Here is my program: http://gist.github.com/384565
Calling ToLower() doesn't do anything by itself. Strings are immutable, meaning that it's impossible to modify an instance of string. The ToLower() function returns a new string, so you have to store that value in a variable (either the same or a new one).
To return the value passed into the function, just create a new string variable.
Like this:
public static string Tester(string input)
{
string pattern = "\\W";
string data = Regex.Replace(input.ToLower(), pattern, String.Empty);
if (data == StringHelper.ReverseString(data))
{
Console.Write(input); Console.Write(" is a Palindrome.");
}
else
{
Console.Write(input); Console.Write(" isn't a Palindrome.");
}
return input;
}

C# Regex Split To Java Pattern split

I have to port some C# code to Java and I am having some trouble converting a string splitting command.
While the actual regex is still correct, when splitting in C# the regex tokens are part of the resulting string[], but in Java the regex tokens are removed.
What is the easiest way to keep the split-on tokens?
Here is an example of C# code that works the way I want it:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
String[] values = Regex.Split("5+10", #"([\+\-\*\(\)\^\\/])");
foreach (String value in values)
Console.WriteLine(value);
}
}
Produces:
5
+
10
I don't know how C# does it, but to accomplish it in Java, you'll have to approximate it. Look at how this code does it:
public String[] split(String text) {
if (text == null) {
text = "";
}
int last_match = 0;
LinkedList<String> splitted = new LinkedList<String>();
Matcher m = this.pattern.matcher(text);
// Iterate trough each match
while (m.find()) {
// Text since last match
splitted.add(text.substring(last_match,m.start()));
// The delimiter itself
if (this.keep_delimiters) {
splitted.add(m.group());
}
last_match = m.end();
}
// Trailing text
splitted.add(text.substring(last_match));
return splitted.toArray(new String[splitted.size()]);
}
This is because you are capturing the split token. C# takes this as a hint that you wish to retain the token itself as a member of the resulting array. Java does not support this.

Categories

Resources