C# how can I check users input - c#

I´m having a string with allowed chars. I´d like that user is only able to use this chars.
My idea was to loop through the unser inputs string and compare char for char. But the problem which I have is when the first char in string allowed is "A" and the first in the users input "B" is, it gives me an error...
Totally confused right now
string allowed = "abc";
string read= Console.ReadLine();
for (int i = 0; i < allowed.Length; i++ )
{
if (allowed[i] == read[i])
{
Console.WriteLine("Okay");
}
else
{
Console.WriteLine("Invalid char on" +index);
}
}

If you wanna check if the user input has any of not allowed characters you need a nested loop, because you wanna compare each char in the user input against the chars in the allowed:
foreach(var r in read)
{
bool isValid = false;
foreach(var c in allowed)
{
// if we found a valid char set isValid to true
if(c == r)
isValid = true;
}
// if it's still false then the current char
// doesn't match any of the allowed chars
// so it's invalid
if(!isValid)
{
Console.WriteLine("the string has invalid char(s)");
break;
}
}
Or, to simplify this you can use LINQ:
bool isInvalid = read.Any(c => !allowed.Contains(c));
If you want to know which chars are invalid, you can use Except method:
var invalidChars = read.Except(allowed);
foreach(var c in invalidChars)
{
Console.WriteLine(c);
}

You either need to search the char of user input within the allowed characters or you could use a regular expression.
Search approach:
private string allowed = "abc";
private string userInput = "some string entered";
bool stringIsValid = false;
for (int i = 0; i < userInput.Length; i++)
{
if (!allowed.IndexOf(userInput[i]))
{
stringIsValid = false;
break; // You can stop the loop upon the first occurance of an invalid char
}
}
Regular expression approach:
private string allowed = "abc";
private string userInput = "some string entered";
bool stringIsValid = Regex.IsMatch(allowed, userInput);
Please note that the regular expression approach is more flexible. If you learn about regular expressions, you will find it very powerful.

You need another loop in your first one:
string allowed = "abc";
string read= Console.ReadLine();
for (int i = 0; i < read.Length; i++ )
{
bool isValid = false;
for (int j = 0; j < allowed.Length; j++)
{
if (read[i] == allowed[j])
{
isValid = true;
break;
}
}
if (isValid)
{
Console.WriteLine("Okay");
}else{
Console.WriteLine("Invalid char on" +index);
}
}
Right now, what you're saying is "every character in read must be exactly the same as in allowed".
What you're trying to say (I think) is "every character in read must be present somewhere in allowed" – that's what the second loop does. It looks for the character in allowed and if it finds it, sets isValid to true. Otherwise the character wasn't found and it's incorrect.
As other answers here state, you can use LINQ or (preferrably) regular expressions (regex) for things like this. I assume this is homework, or you're new to C# or programming, so I provided a basic answer to (hopefully) help you understand what's not working currently with your code.
If this should indeed be a homerwok or studying-related question, then let me recommend you put that in your question next time, for it's not forbidden to ask about homework.
The "real world" solutions we would use are of no help to you if you're trying to figure out the basics, so if we know it's about learning stuff then we'll provide answers that are more useful for you.

When using a collection to store not allowed items (instead of a plain string) it opens a whole new spectrum of LINQ expressions you can use:
public static void Main(string[] args)
{
var allowed = new List<string> { "a", "b", "c" };
var read = Console.ReadLine().Select(c => c.ToString()).ToList();
if (read.All(allowed.Contains))
{
Console.WriteLine("Okay");
}
else
{
var firstNotAllowed = read.First(a => !allowed.Contains(a));
var firstIndex = read.FindIndex(a => !allowed.Contains(a));
Console.WriteLine("Invalid char: {0}, at index: {1}", firstNotAllowed, firstIndex);
}
}

Related

Check if a word exists in another string in c# without using any inbuilt function

string sentence = "This is a goodday";
string word = "good";
I know this can be done with .Contains() method. I was asked in an interview how to do it without contains method.
how to do it in english.
pick the first letter of word.
walk down sentence a character at a time till you find that letter
now look at the next letters in sentence to see if they are the rest of that word
yes - done
no - keep going
the thing to use is that word[x] is the x-1th character of word, so you just need 2 indexes and a loop or 2
Q: Check if a word exists in another string in c# without using any inbuilt function
A: Tricky
It depends on how detailed that "any inbuilt function" really is.
In general the algorithm is simple:
Loop through the string you're searching in
for each position, see if you've found the word
you do this by looping through all the characters in what we're looking for
and compare each character from the first string with one from the second
if they all matched, we've found a match
but then ... "without using any inbuilt function".
I assume this would mean, do not use the obvious ones, such as Contains, IndexOf, a regular expression, all those things.
But taken to the extreme, does that mean I cannot even know how long the strings are? Is s.Length a built-in function? And thus not allowed?
public bool Contains(string value, string whatWereLookingFor)
{
return IndexOf(value, whatWereLookingFor) >= 0;
}
public int Length(string s)
{
int result = 0;
for (int i = 0; i <= 2147483647; i++)
{
try
{
char c = s[i];
}
catch (IndexOutOfRangeException)
{
break;
}
result = i + 1;
}
return result;
}
public int IndexOf(string value, string whatWereLookingFor)
{
int iMax = Length(value);
int whatMax = Length(whatWereLookingFor);
for (int i = 0; i <= iMax - whatMax; i++)
{
bool isMatch = true;
for (int j = 0; j < whatMax; j++)
{
if (value[i + j] != whatWereLookingFor[j])
{
isMatch = false;
break;
}
}
if (isMatch)
return i;
}
return -1;
}
How about using a for loop?
Loop through the sentence checking for the first character of the work. Once you find that check for the next character of the word until you find the whole word (done - word exists in sentence) or a different character so you start again looking for the first character of the word until you run out of characters.
As the comments say, it would have been nicer to let us know what you answered.
try this:
static bool checkString(string inputString="",string word="")
{
bool returV=false;
if(inputString =="" || word=="")
return false;
int intexcS=0;
Dictionary<int,string> d = new Dictionary<int, string>();
foreach (char cW in word)
{
foreach (char cS in inputString)
{
if(cW==cS){
if(!d.ContainsKey(intexcS) && d.Count<word.Length){
d.Add(intexcS,cW.ToString());
}
}
intexcS++;
}
intexcS=0;
}
int i=0;
foreach(var iitem in d) { if(iitem.Value!=word[i].ToString()) returV=false; else returV=true; i++; }
return returV;
}

How can I add a character to a string based on another string in C#?

I need to create a function that receives two strings, representing the word to be completed and the reference word, as well as a character corresponding to the proposed letter, and returns a string corresponding to the word to be completed in which all occurrences of the proposed letter have been added, relative to the reference word.
Example: CompleterMot (".. IM ..", "ANIMAL", 'A') should return "A.IMA.".
I don't understand how I can add all occurrences of the letter in the word that will be completed.
static string CompleterMot(string motincomplet, string motoriginal, char lettrepropos)
{
string output = " ";
for (int i = 0; i < motoriginal.Length; i++)
{
if((motoriginal[i] == lettrepropos))
{
output = motincomplet;
if(output[i] != lettrepropos)
output += (char)(lettrepropos);
}
}
return output;
}
In final I had ..IM..A and I don't know how to fix my code.
In your loop, you are doing this : output = motincomplet; this override the previous result. Then you append the expected letter to the output that gives "..IM.." + 'A' as result.
You can use a StringBuilder for string manipulation, that's pretty nice and allow you to directly change a character at a given index :
static string CompleterMot(string motincomplet, string motoriginal, char lettrepropos)
{
var sb = new System.Text.StringBuilder(motincomplet);
for (int i = 0; i < motoriginal.Length; i++)
{
if (motoriginal[i] == lettrepropos)
{
sb[i] = lettrepropos;
}
}
return sb.ToString();
}

Console Array Char Insert User Input

I added the initialization to show the array. When it hits the else and tries to insert the input into the array it throws an exception. I have tried several different examples online, and have not yet found a solution. I am appreciative of any help that is given.
private char[] currentMisses;
public int makeTurn()
{
// Ask the user for a guess
Console.Write("Choose A Letter: ");
// Get the input from the user
var currentGuess = Console.ReadKey();
char input = currentGuess.KeyChar;
input = Char.ToUpper(input);
// Do input conversions
while (!char.IsLetter(input))
{
//Console.Write(input);
currentGuess = Console.ReadKey(true);
input = currentGuess.KeyChar;
input = Char.ToUpper(input);
}
// See if it exists in our word
bool test = false;
test = currentWord.Contains(input);
Console.WriteLine("Hello" + input);
// If we didn't find it
if (!test)
{
if (currentMisses != null)
{
Console.WriteLine("WORD");
// Make sure it does not currently exist in the misses array
for (int i = 0; i < currentMisses.Length; i++)
{
if (currentMisses[i] != input)
{
currentMisses[i] = input;
Console.WriteLine("In Loop");
}
Console.WriteLine("Not in Loop");
}
}
else
{
/* This is where I am trying to insert the input from the user to the char array currentMisses, I've tried multiple ways and it seems simple but I hit a roadblock*/
currentMisses[0] = input;
}
Your logic is off a bit here. In your if statement you are saying "if my array is not null" then loop over the array else (i.e. You have a null array) "try to insert into that null array"
You need to initialize your array with something like:
private char[] currentMisses = new char[x]
Where x is how big you need your array to be.
I'd change this:
private char[] currentMisses
to this:
int numberOfWrongGuessesAllowed = 10 //however many guess you allow user to make
private char[] currentMisses = new char[numberOfWrongGuessesAllowed]

Looping until end of String C#

I have a string (input is performed by user) which has an expression to be checked against a regex pattern matcher.
I wish to loop through the String until EOF. I was thinking of using input.Length but then I don't know how to continue to compare the number. If the whole string is correct against the pattern then it returns TRUE, otherwise FALSE. This is where I arrived till now.
private void checkInput (String input)
{
{
String acceptedInput = "(?=\\()|(?<=\\)\\d)";
// Need a loop until End of String
// (while ?)
{
foreach (Match match in Regex.Matches(input, acceptedInput))
{
outputDialog.AppendText("Correct");
}
return true;
}
return false;
}
}
Is there any way to do it please?
Thank you
To loop over each char in a string:
for (int i = 0; i < stringVariable.Length; i++)
{
char x = stringVariable[i]; //is the i'th character of the string
}
But that approach makes no sense if your using RegEx, which generally work on entire strings.
Maybe explain what your trying to achieve?
Use String.ToCharArray
i.e.
char[] array = input.ToCharArray();
for (int i = 0; i < array.Length; i++)
{
var letter = array[i];//here is the individual character
}
you don't need to loop:
string toAvoid = "$%&#";
if (input.IndexOfAny(toAvoid.ToCharArray()) != -1)
{
// the input contains forbidden characters
}

Char/String comparison

I'm trying to have a suggestion feature for the search function in my program eg I type janw doe in the search section and it will output NO MATCH - did you mean jane doe? I'm not sure what the problem is, maybe something to do with char/string comparison..I've tried comparing both variables as type char eg char temp -->temp.Contains ...etc but an error appears (char does not contain a definition for Contains). Would love any help on this! 8)
if (found == false)
{
Console.WriteLine("\n\nMATCH NOT FOUND");
int charMatch = 0, charCount = 0;
string[] checkArray = new string[26];
//construction site /////////////////////////////////////////////////////////////////////////////////////////////////////////////
for (int controlLoop = 0; controlLoop < contPeople.Length; controlLoop++)
{
foreach (char i in userContChange)
{
charCount = charCount + 1;
}
for (int i = 0; i < userContChange.Length; )
{
string temp = contPeople[controlLoop].name;
string check=Convert.ToString(userContChange[i]);
if (temp.Contains(check))
{
charMatch = charMatch + 1;
}
}
int half = charCount / 2;
if (charMatch >= half)
{
checkArray[controlLoop] = contPeople[controlLoop].name;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
Console.WriteLine("Did you mean: ");
for (int a = 0; a < checkArray.Length; a++)
{
Console.WriteLine(checkArray[a]);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
A string is made up of many characters. A character is a primitive, likewise, it doesn't "contain" any other items. A string is basically an array of characters.
For comparing string and characters:
char a = 'A';
String alan = "Alan";
Debug.Assert(alan[0] == a);
Or if you have a single digit string.. I suppose
char a = 'A';
String alan = "A";
Debug.Assert(alan == a.ToString());
All of these asserts are true
But, the main reason I wanted to comment on your question, is to suggest an alternative approach for suggesting "Did you mean?". There's an algorithm called Levenshtein Distance which calculates the "number of single character edits" required to convert one string to another. It can be used as a measure of how close two strings are. You may want to look into how this algorithm works because it could help you.
Here's an applet that I found which demonstrates: Approximate String Matching with k-differences
Also the wikipedia link Levenshtein distance
Char type cannot have .Contains() because is only 1 char value type.
In your case (if i understand), maybe you need to use .Equals() or the == operator.
Note: for compare String correctly, use .Equals(),
the == operator does not work good in this case because String is reference type.
Hope this help!
char type dosen't have the Contains() method, but you can use iit like this: 'a'.ToString().Contains(...)
if do not consider the performance, another simple way:
var input = "janw doe";
var people = new string[] { "abc", "123", "jane", "jane doe" };
var found = Array.BinarySearch<string>(people, input);//or use FirstOrDefault(), FindIndex, search engine...
if (found < 0)//not found
{
var i = input.ToArray();
var target = "";
//most similar
//target = people.OrderByDescending(p => p.ToArray().Intersect(i).Count()).FirstOrDefault();
//as you code:
foreach (var p in people)
{
var count = p.ToArray().Intersect(i).Count();
if (count > input.Length / 2)
{
target = p;
break;
}
}
if (!string.IsNullOrWhiteSpace(target))
{
Console.WriteLine(target);
}
}

Categories

Resources