Compare similarity of two Strings for name verification - c#

I need help with a program that im using to verify a user's names. there has to be a certain level of leniency to accept differences like hyphens, spaces and apostrophes. Currently im removing useless characters to compare the strings but names of completely different characters with the same length are being Ok'd. how do i check to see the names are suing similar characters. after the useless ones have been removed and mushed together.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace name_v
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter first name");
string firstname = Console.ReadLine();
Console.WriteLine("Enter 2nd name");
string secondname = Console.ReadLine();
if (firstname == secondname)
{
Console.WriteLine("Names are exactly the same");
Console.ReadLine();
}
else
{
Console.WriteLine("press enter to Compare");
Console.ReadLine();
int numFirstName = firstname.Length;
int numSecondName = secondname.Length;
Console.WriteLine("# in 1st = " + numFirstName);
Console.WriteLine("# in 2nd = " + numSecondName);
Console.ReadLine();
firstname = firstname.Replace(" ", "").Replace("-", "").Replace("'", "").Replace(".", "").ToUpper();
secondname = secondname.Replace(" ", "").Replace("-", "").Replace("'", "").Replace(".", "").ToUpper();
Console.WriteLine("Names to be compared as");
Console.WriteLine(firstname);
Console.WriteLine(secondname);
numFirstName = firstname.Length;
numSecondName = secondname.Length;
Console.WriteLine("# in 1st = " + numFirstName);
Console.WriteLine("# in 2nd = " + numSecondName);
Console.ReadLine();
int nameLengthDif = numFirstName - numSecondName;
if (firstname == secondname)
{
Console.WriteLine("Names are the same");
Console.ReadLine();
}
else
{
Console.WriteLine("Names are not the same");
Console.ReadLine();
if (nameLengthDif < 3)
{
Console.WriteLine("But Close enough");
Console.ReadLine();
}
else
{
Console.WriteLine("And not Close enough");
Console.ReadLine();
}
}
}
}
}
}

#TestWell gave a great solution for determining character difference, but I just want to show you a much better way to strip characters than stringing .Replace() over and over and over again:
You can just add/remove chars from this array:
private char[] invalid = new char[] {' ','-','_','.'};
private static string cleanString(string input)
{
return new string(input.Where(x => !invalid.Contains(x)).ToArray()).ToLower();
}
usage:
firstname = cleanString(firstname);
or as an extension method:
namespace CustomExtensions
{
public static class StringExtension
{
private static char[] invalid = new char[] {' ','-','_','.'};
public static string CleanString(this string y)
{
return new string(y.Where(x => !invalid.Contains(x)).ToArray()).ToLower();
}
}
}
usage:
firstname = firstname.CleanString();

try as following :
char[] firstName = firstName.ToCharArray();
char[] lastName = lastName.ToCharArray();
char[] res = firstName.Except(lastName).ToArray();
if(res.Length < 1)
{
res = lastName.Except(firstName).ToArray();
}
nameLengthDif = res.Length

How about
private static int GetDifferenceCount(string firstName, string lastName)
{
int differences;
string longestString = firstName;
if (longestString.Length < lastName.Length)
longestString = lastName;
for (int i = 0; i < longestString.Length; i++)
{
try
{
if (firstName.Substring(i, 1) != lastName.Substring(i, 1))
differences++;
}
catch
differences++;
}
return differences;
}
To return number of different characters. You could then say
if (GetDifferenceCount(firstName, lastName) >= 2)
// Do something
Completing an action if 2 or more characters are different.

Related

How can i get index of two same character in string?

I want to create simple console wingman game.My error is that if i try get pos of 2 same character in word i get only one and the other is skipped.
For example Tomatoe.
Console output:
Tomatoe
_ o m a t _ _
I know i didnt use live didnt have time for that i do it layter.
class Program {
static string[] word = { "Pineapple", "Apple" , "Tomatoe" , "Pizza"};
static int wordIndex = 0;
static char[] randomWord;
static bool guessing = true;
public static void Main(string[] args)
{
int lives = 3;
Console.OutputEncoding = Encoding.UTF8;
Console.InputEncoding = Encoding.UTF8;
Random r = new Random();
wordIndex = r.Next(word.Length);
randomWord = word[wordIndex].ToLower().ToCharArray();
char[] randomWordcensored = new char[randomWord.Length];
for (int i = 0; i < randomWord.Length; i++)
{
randomWordcensored[i] = '_';
}
Console.WriteLine("Hello");
foreach (var item in randomWordcensored)
{
Console.Write(item + " ");
}
Console.WriteLine();
Console.WriteLine("Please Enter character:");
while (guessing = true)
{
int g = 0;
char userinput;
bool security = char.TryParse(Console.ReadLine() ,out userinput);
if (security == true) {
if (randomWord.Contains(userinput))
{ //help needed
g = (word[wordIndex].ToString().IndexOf(userinput) == -1 ? 0 : word[wordIndex].ToString().IndexOf(userinput));
randomWordcensored[g] = userinput;
Console.WriteLine("Good :) " + g);
foreach (var item in randomWordcensored)
{
Console.Write(item + " ");
}
}
else
{
lives--;
Console.WriteLine("Wrong!\n-Lives:" + lives);
}
}
else
{
Console.WriteLine("Enter only one charracter!");
}
}
}
}
You'll want to handle user input that might be different casing and such. Because of that it's easiest to just visit every character in the random word just once.
Here's a REPL that I made to solve this:
using System;
using System.Collections.Generic;
class MainClass {
public static void Main (string[] args) {
var word = "Tomato";
var input = "t";
var letter = input.ToLower()[0];
var indices = new List<int>();
for(var i = 0; i < word.Length; i++)
if (word.ToLower()[i] == letter)
indices.Add(i);
Console.WriteLine($"Secret word: {word}");
Console.WriteLine($"User guess: {input}");
Console.WriteLine($"Found at {String.Join(", ", indices)}");
}
}
and its output:
Mono C# compiler version 4.0.4.0
Secret word: Tomato
User guess: t
Found at 0, 4

English to Pig Latin C# Console Application

I'm having some trouble making an applicaton in c# converting english to pig latin. I have everything else down except for when it comes to making the getTranslation method for it. For some odd reason I just can't figure it out. IF someone could give me some ideas I would appreciate it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace W15M5A2_CPigLatinApp
{
class W15M5A2_CPigLatinAppProgram
{
static void Main(string[] args)
{
string inputPhrase = "";
string[] phraseOut;
DisplayInfo();
inputPhrase = GetPhrase();
while (inputPhrase != "")
{
Console.WriteLine(" ");
phraseOut = GetTranslation(inputPhrase);
DisplayResults(inputPhrase, phraseOut);
inputPhrase = GetPhrase();
}
Console.ReadKey();
}
public static void DisplayInfo()
{
Console.WriteLine("********************************************************" +
"\n*** You will be prompted to enter a string of ***" +
"\n*** words. The phrase will be converted into a ***" +
"\n*** pseudo Pig Latin with results displayed. ***" +
"\n\n*** Enter as many strings as you would like. ***" +
"\n********************************************************\n\n");
Console.Write("\n\n\n Press any key when you are ready to begin...");
Console.ReadKey();
Console.Clear();
}
public static string GetPhrase()
{
string inputPhrase;
Console.WriteLine("Enter a phrase or group of words " +
"\nTo Exit, press the Enter key\n");
inputPhrase = Console.ReadLine();
return inputPhrase;
}
// GetTranslation method
public static string[] GetTranslation(string phraseIn)
{
}
public static void DisplayResults(string input, string[] output)
{
Console.Clear();
Console.WriteLine("Original Phrase: " + input + "\n");
Console.Write("\nNew Phrase: ");
foreach (string i in output)
{
Console.Write(i + " ");
}
Console.WriteLine("\n");
}
}
}
public static string[] GetTranslation(string phraseIn)
{
string vow = "aeiouyAEIOUY";
var splitted = phraseIn.Split(new[] {" "}, StringSplitOptions.None);
List< string> ret = new List<string>();
foreach (string split in splitted)
{
string vows = string.Empty;
string cons = string.Empty;
for (var i = 0; i < split.Length; i++)
{
char ch = split[i];
if (vow.Contains(ch))
{
vows += ch;
}
else
{
cons += ch;
}
}
ret.Add(cons + vows + "ay");
}
return ret.ToArray();
}
This is a (little bit hacky) solution. I tested it with the examples from Wiki.
public static string ToPigLatin(string word)
{
string result = string.Empty;
string pigSuffixVowelFirst = "yay";
string pigSuffixConstanantsFirst = "ay";
string vowels = "aeiouAEIOU";
if(vowels.Contains(word.First()))
{
result = word + pigSuffixVowelFirst;
}
else
{
int count = 0;
string end = string.Empty;
foreach(char c in word)
{
if (!vowels.Contains(c))
{
end += c;
count++;
}
else
{
break;
}
}
result = word.Substring(count) + end + pigSuffixConstanantsFirst;
}
return result;
}
Use at your own peril :)

Can't get my method to upper case my string arrays

The whole program is listed after, but the only problem i have with it is the ToUppers() method. I just want this method to iterate over each string in my array, and then make everything upper case.
private static string[] ToUppers(string[] stringToUpperArrays)
{
string stringer;
foreach (string value in stringToUpperArrays)
{
stringer = value.ToUpper(); // <== this line highlighted
Console.WriteLine(stringer);
}
return stringToUpperArrays;
}
The program executes after it prints it on the console, and it lists a NullReferenceException, and highlights the stringer = value.ToUpper(); line
The whole program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utility;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//Mark Bouwman
//CNT A01
//ICA18
//April 2nd
string answer;
int numInArray;
string[] stringArrays;
string[] stringArraysToDisplay;
string[] stringToUpperArrays;
//TITLE
Console.WriteLine("\t\tStringy");
do
{
numInArray = Utility.Utility.GetInt(2, 10, "Enter the size of the array from 2 to 10: ");
stringArrays = CreateArray(numInArray);
stringArraysToDisplay = Display(stringArrays);
stringToUpperArrays = ToUppers(stringArrays);
//aksing to run program again
Console.Write("Run program again? yes or no: ");
answer = Console.ReadLine();
}
while (answer.Equals("yes", StringComparison.CurrentCultureIgnoreCase));
}
private static string[] CreateArray(int numInArray)
{
int index;
string[] stringArray;
stringArray = new string[(numInArray + 1)];
for (index = 0; index < numInArray; ++index)
{
Console.Write("Enter string #" + (index + 1) + " ");
stringArray[index] = Console.ReadLine();
}
return stringArray;
}
private static string[] Display(string[] stringArraysDisplay)
{
foreach (string value in stringArraysDisplay)
{
Console.WriteLine(value);
}
return stringArraysDisplay;
}
private static string[] ToUppers(string[] stringToUpperArrays)
{
string stringer;
foreach (string value in stringToUpperArrays)
{
stringer = value.ToUpper();
Console.WriteLine(stringer);
}
return stringToUpperArrays;
}
}
}
In CreateArray you define the array to size of numInArray + 1 but you fill the array only with numInArray strings, i.e. the last index is empty. When you try value.ToUpper(); on the empty index you get the exception.
In CreateArray change
stringArray = new string[(numInArray + 1)];
To
stringArray = new string[numInArray];
Or change
for (index = 0; index < numInArray; ++index)
{
Console.Write("Enter string #" + (index + 1) + " ");
stringArray[index] = Console.ReadLine();
}
To
for (index = 0; index < stringArray.Length; ++index)
{
Console.Write("Enter string #" + (index + 1) + " ");
stringArray[index] = Console.ReadLine();
}
You should erase the + 1 when you are initializing the array
stringArray = new string[(numInArray)];
in this method
private static string[] CreateArray(int numInArray)

Remove text between quotes

I have a program, in which you can input a string. But I want text between quotes " " to be removed.
Example:
in: Today is a very "nice" and hot day.
out: Today is a very "" and hot day.
Console.WriteLine("Enter text: ");
text = Console.ReadLine();
int letter;
string s = null;
string s2 = null;
for (s = 0; s < text.Length; letter++)
{
if (text[letter] != '"')
{
s = s + text[letter];
}
else if (text[letter] == '"')
{
s2 = s2 + letter;
letter++;
(text[letter] != '"')
{
s2 = s2 + letter;
letter++;
}
}
}
I don't know how to write the string without text between quotes to the console.
I am not allowed to use a complex method like regex.
This should do the trick. It checks every character in the string for quotes.
If it finds quotes then sets a quotesOpened flag as true, so it will ignore any subsequent character.
When it encounters another quotes, it sets the flag to false, so it will resume copying the characters.
Console.WriteLine("Enter text: ");
text = Console.ReadLine();
int letterIndex;
string s2 = "";
bool quotesOpened = false;
for (letterIndex= 0; letterIndex< text.Length; letterIndex++)
{
if (text[letterIndex] == '"')
{
quotesOpened = !quotesOpened;
s2 = s2 + text[letterIndex];
}
else
{
if (!quotesOpened)
s2 = s2 + text[letterIndex];
}
}
Hope this helps!
A take without regular expressions, which I like better, but okay:
string input = "abc\"def\"ghi";
string output = input;
int firstQuoteIndex = input.IndexOf("\"");
if (firstQuoteIndex >= 0)
{
int secondQuoteIndex = input.IndexOf("\"", firstQuoteIndex + 1);
if (secondQuoteIndex >= 0)
{
output = input.Substring(0, firstQuoteIndex + 1) + input.Substring(secondQuoteIndex);
}
}
Console.WriteLine(output);
What it does:
It searches for the first occurrence of "
Then it searches for the second occurrence of "
Then it takes the first part, including the first " and the second part, including the second "
You could improve this yourself by searching until the end of the string and replace all occurrences. You have to remember the new 'first index' you have to search on.
string text = #" Today is a very ""nice"" and hot day. Second sentense with ""text"" test";
Regex r = new Regex("\"([^\"]*)\"");
var a = r.Replace(text,string.Empty);
Please try this.
First we need to split string and then remove odd items:
private static String Remove(String s)
{
var rs = s.Split(new[] { '"' }).ToList();
return String.Join("\"\"", rs.Where(_ => rs.IndexOf(_) % 2 == 0));
}
static void Main(string[] args)
{
var test = Remove("hello\"world\"\"yeah\" test \"fhfh\"");
return;
}
This would be a possible solution:
String cmd = "This is a \"Test\".";
// This is a "".
String newCmd = cmd.Split('\"')[0] + "\"\"" + cmd.Split('\"')[2];
Console.WriteLine(newCmd);
Console.Read();
You simply split the text at " and then add both parts together and add the old ". Not a very nice solution, but it works anyway.
€dit:
cmd[0] = "This is a "
cmd[1] = "Test"
cmd[2] = "."
You can do it like this:
Console.WriteLine("Enter text: ");
var text = Console.ReadLine();
var skipping = false;
var result = string.Empty;
foreach (var c in text)
{
if (!skipping || c == '"') result += c;
if (c == '"') skipping = !skipping;
}
Console.WriteLine(result);
Console.ReadLine();
The result string is created by adding characters from the original string as long we are not between quotes (using the skipping variable).
Take all indexes of quotes remove the text between quotes using substring.
static void Main(string[] args)
{
string text = #" Today is a very ""nice"" and hot day. Second sentense with ""text"" test";
var foundIndexes = new List<int>();
foundIndexes.Add(0);
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '"')
foundIndexes.Add(i);
}
string result = "";
for(int i =0; i<foundIndexes.Count; i+=2)
{
int length = 0;
if(i == foundIndexes.Count - 1)
{
length = text.Length - foundIndexes[i];
}
else
{
length = foundIndexes[i + 1] - foundIndexes[i]+1;
}
result += text.Substring(foundIndexes[i], length);
}
Console.WriteLine(result);
Console.ReadKey();
}
Output: Today is a very "" and hot day. Second sentense with "" test";
Here dotNetFiddle

How to add exception for errors(try, catch)

This is my code for some console app. First thing that doesn't work very well is method SwitchLetters. When I input some string and press enter every letter goes to new line. I don't know why. Also i don't know how to display lower and upper case in methods PrintBeforeSwitch and PrintAfterSwitch. And Exception how to use try and catch for some exception and which exception to use...
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please input string");
string input = Console.ReadLine();
NewString ns = new NewString();
StringOperation so = new StringOperation();
ns.SwitchLetters(input);
so.PrintBeforeSwitch(input);
so.PrintAfterSwitch(input);
}
}
class NewString
{
private string newString;
public string _NewString
{
get
{
return newString;
}
set
{
newString = value;
}
}
public void SwitchLetters(string newStr)
{
StringBuilder myString = new StringBuilder();
for (int i = 0; i < newStr.Length; i++)
{
if (char.IsUpper(newStr, i))
myString.Append(char.ToLower(newStr[i]));
else if (char.IsLower(newStr, i))
myString.Append(char.ToUpper(newStr[i]));
else
myString.Append(newStr[i]);
Console.WriteLine(myString.ToString());
Console.ReadLine();
Console.WriteLine(newStr.ToUpper());
}
}
}
class StringOperation
{
private string inputString;
//public NewString newSrt;
public string InputString
{
get
{
return inputString;
}
set
{
inputString = value;
}
}
public int VocalNumber(string str)
{
int num;
return num = str.Count(a => "aeiouAEIOU".Contains(a));
}
public int SpaceNumber(string str)
{
int num;
return num = str.Count(b => b == ' ');
}
public List<int> LowerUpperCaseLattersNumber(string str)
{
int counterLower = 0;
int counterUpper = 0;
List<int> counter = new List<int>();
foreach (char value in str)
{
if (char.IsLower(value))
{
counterLower++;
}
else
{
counterUpper++;
}
}
counter.Add(counterLower);
counter.Add(counterUpper);
Console.WriteLine("Number of small latters is: {0}", counterLower);
Console.WriteLine("Number of big letters is: {0}", counterUpper);
return counter;
}
public string SwitchVocals(ref string str)
{
string vocals = str.Replace("a", "x").Replace("e", "x").Replace("i", "x").Replace("o", "x").Replace("u", "x").Replace("A", "X").Replace("E", "X").Replace("I", "X").Replace("O", "X").Replace("U", "X");
Console.WriteLine(vocals);
return vocals;
}
public void PrintBeforeSwitch(string str)
{
Console.WriteLine(str);
Console.WriteLine("Information about string:");
Console.WriteLine("Number of vowels: {0}", VocalNumber(str));
Console.WriteLine("Number of space: {0}", SpaceNumber(str));
Console.WriteLine("Number of small latters is: {0}", LowerUpperCaseLattersNumber(str));
Console.WriteLine("Number of big letters is: {0}", LowerUpperCaseLattersNumber(str));
Console.ReadLine();
}
public void PrintAfterSwitch(string str)
{
SwitchVocals(ref str);
Console.WriteLine("Information about string after switch:");
Console.WriteLine("Number of vowels: {0}", VocalNumber(str));
Console.WriteLine("Number of space: {0}", SpaceNumber(str));
Console.WriteLine("Number of small latters is: {0}", LowerUpperCaseLattersNumber(str));
Console.WriteLine("Number of big letters is: {0}", LowerUpperCaseLattersNumber(str));
Console.ReadLine();
}
}
Here is an idea how to do the exception:
public void SwitchLetters(string newStr)
{
try
{
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();//this stops the program so you can read the error
}
}
I think you had the two lines swapped around so.PrintBeforeSwitch and ns.SwitchLetters
static void Main(string[] args)
{
Console.WriteLine("Please input string");
string input = Console.ReadLine();
NewString ns = new NewString();
StringOperation so = new StringOperation();
so.PrintBeforeSwitch(input);
ns.SwitchLetters(input);
so.PrintAfterSwitch(input);
}
If you use Console.WriteLine("some string here"); it will do exactly as it says, write line. However you can use Console.Write("some string here"); and it should add the text/string onto the existing line.
Can you please give us more information by what you mean "First thing that doesn't work very well is method SwitchLetters..." what should it do? What does it currently do?
To resolve your issue in the comment below remove the Console.ReadLine()
public void SwitchLetters(string newStr)
{
StringBuilder myString = new StringBuilder();
for (int i = 0; i < newStr.Length; i++)
{
if (char.IsUpper(newStr, i))
myString.Append(char.ToLower(newStr[i]));
else if (char.IsLower(newStr, i))
myString.Append(char.ToUpper(newStr[i]));
else
myString.Append(newStr[i]);
Console.WriteLine(myString.ToString());
//Console.ReadLine(); This line needs to be removed
Console.WriteLine(newStr.ToUpper());
}
}

Categories

Resources