Array 11th index - c#

Ok so I was reworking the current infrastructure for my AI and I created it into an array. But i'm not sure how to get the 11th value to be recognized in the array "dictonary"
Here is the code!
string name = "Jarvis";
string[] dictionary = new string[] { "hello", "how", "are", "you", "sup", "wake", "up", "daddys", "home", "what", "version", "whats", "your" };
bool helloflag = false;
void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
string code = "";
//ResultText = "Hello how are you"
string[] words = e.Result.Text.Split(' ');
//words = ["Hello", "how", "are", "you"]
foreach (string word in words)
{
for (int index = 0; index < dictionary.Count(); index++)
{
if (word == dictionary[index])
{
code += index.ToString();
}
}
}
//code = "123"; //how are you
//code = "236"; //are you up
//HELLO
if ((code == "0") || (code == "4"))
{
Jarvis.Speak("Hello sir");
helloflag = true;
} else if ((helloflag == true ) && (code == "123"))
{
Jarvis.Speak("im good sir");
helloflag = false;
}
This is part of the .NET speech API, but is using an array to call the words you say.

When you're adding to code, you need to put a separator between the codes. Otherwise, you can't tell whether 12 is word 1 followed by word 2, or word 12. E.g.
code += index.toString() + " ";
Then you can do things like:
if (code == "10 9 2 3 ") // whats version are you
Don't forget the space at the end.

Prob it is more flexible to store your code values in array, e.g.:
var code = new List<int>();
....
code.Add(index);
...
if(code.SequenceEqual(new int[] {1, 2, 3})
{
...

Related

C# Get Initials of DisplayName

I'm trying to extract initials from a display name to be used to display their initials.
I'm finding it difficult because the string is one value containing one word or more. How can I achieve this?
Example:
'John Smith' => JS
'Smith, John' => SJ
'John' => J
'Smith' => S
public static SearchDto ToSearchDto(this PersonBasicDto person)
{
return new SearchDto
{
Id = new Guid(person.Id),
Label = person.DisplayName,
Initials = //TODO: GetInitials Code
};
}
I used the following solution: I created a helper method which allowed me to test for multiple cases.
public static string GetInitials(this string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return string.Empty;
}
string[] nameSplit = name.Trim().Split(new string[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries);
var initials = nameSplit[0].Substring(0, 1).ToUpper();
if (nameSplit.Length > 1)
{
initials += nameSplit[nameSplit.Length - 1].Substring(0, 1).ToUpper();
}
return initials;
}
Or just another variation as an extension method, with a small amount of sanity checking
Given
public static class StringExtensions
{
public static string GetInitials(this string value)
=> string.Concat(value
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Where(x => x.Length >= 1 && char.IsLetter(x[0]))
.Select(x => char.ToUpper(x[0])));
}
Usage
var list = new List<string>()
{
"James blerg Smith",
"Michael Smith",
"Robert Smith 3rd",
"Maria splutnic Garcia",
"David Smith",
"Maria Rodriguez",
"Mary Smith",
"Maria Hernandez"
};
foreach (var name in list)
Console.WriteLine(name.GetInitials());
Output
JBS
MS
RS
MSG
DS
MR
MS
MH
Full Demo Here
Simple and easy to understand code and handles names which contain first, middle and last name such as "John Smith William".
Test at: https://dotnetfiddle.net/kmaXXE
Console.WriteLine(GetInitials("John Smith")); // JS
Console.WriteLine(GetInitials("Smith, John")); // SJ
Console.WriteLine(GetInitials("John")); // J
Console.WriteLine(GetInitials("Smith")); // S
Console.WriteLine(GetInitials("John Smith William")); // JSW
Console.WriteLine(GetInitials("John H Doe")); // JHD
static string GetInitials(string name)
{
// StringSplitOptions.RemoveEmptyEntries excludes empty spaces returned by the Split method
string[] nameSplit = name.Split(new string[] { "," , " "}, StringSplitOptions.RemoveEmptyEntries);
string initials = "";
foreach (string item in nameSplit)
{
initials += item.Substring(0, 1).ToUpper();
}
return initials;
}
How about the following:
void Main()
{
Console.WriteLine(GetInitials("John Smith"));
Console.WriteLine(GetInitials("Smith, John"));
Console.WriteLine(GetInitials("John"));
Console.WriteLine(GetInitials("Smith"));
}
private string GetInitials(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return string.Empty;
}
var splitted = name?.Split(' ');
var initials = $"{splitted[0][0]}{(splitted.Length > 1 ? splitted[splitted.Length - 1][0] : (char?)null)}";
return initials;
}
Output:
JS - SJ - J - S
the code below is from here. what the code does is take the first letter of every word from the string and outputs it as capital letters.
static void printInitials(String name)
{
if (name.Length == 0)
return;
// Since touuper() returns int,
// we do typecasting
Console.Write(Char.ToUpper(name[0]));
// Traverse rest of the string and
// print the characters after spaces.
for (int i = 1; i < name.Length - 1; i++)
if (name[i] == ' '&((i + 1)!=name.Length))
Console.Write(" " + Char.ToUpper(name[i + 1]));
}

text parsing application c# without third party libraries

For example, there is a line:
name, tax, company.
To separate them i need a split method.
string[] text = File.ReadAllLines("file.csv", Encoding.Default);
foreach (string line in text)
{
string[] words = line.Split(',');
foreach (string word in words)
{
Console.WriteLine(word);
}
}
Console.ReadKey();
But how to divide if in quotes the text with a comma is indicated:
name, tax, "company, Ariel";<br>
"name, surname", tax, company;<br> and so on.
To make it like this :
Max | 12.3 | company, Ariel
Alex, Smith| 13.1 | Oriflame
It is necessary to take into account that the input data will not always be in an ideal format (as in the example). That is, there may be 3 quotes in a row or a string without commas. The program should not fall in any case. If it is impossible to parse, then issue a message about it.
Split using double quotes first. And Split using comma on the first string.
You can use TextFieldParser from Microsoft.VisualBasic.FileIO
var list = new List<Data>();
var isHeader=true;
using (TextFieldParser parser = new TextFieldParser(filePath))
{
parser.Delimiters = new string[] { "," };
while (true)
{
string[] parts = parser.ReadFields();
if(isHeader)
{
isHeader = false;
continue;
}
if (parts == null)
break;
list.Add(new Data
{
People = parts[0],
Tax = Double.Parse(parts[1]),
Company = parts[2]
});
}
}
Where Data is defined as
public class Data
{
public string People{get;set;}
public double Tax{get;set;}
public string Company{get;set;}
}
Please note you need to include Microsoft.VisualBasic.FileIO
Example Data,
Name,Tax,Company
Max,12.3,"company, Ariel"
Ariel,13.1,"company, Oriflame"
Output
Here's a bit of code that might help, not the most efficient but I use it to 'see' what is going on with the parsing if a particular line is giving trouble.
string[] text = File.ReadAllLines("file.csv", Encoding.Default);
string[] datArr;
string tmpStr;
foreach (string line in text)
{
ParseString(line, ",", "!####!", out datArr, out tmpStr)
foreach(string s in datArr)
{
Console.WriteLine(s);
}
}
Console.ReadKey();
private static void ParseString(string inputString, string origDelim, string newDelim, out string[] retArr, out string retStr)
{
string tmpStr = inputString;
retArr = new[] {""};
retStr = "";
if (!string.IsNullOrWhiteSpace(tmpStr))
{
//If there is only one Quote character in the line, ignore/remove it:
if (tmpStr.Count(f => f == '"') == 1)
tmpStr = tmpStr.Replace("\"", "");
string[] tmpArr = tmpStr.Split(new[] {origDelim}, StringSplitOptions.None);
var inQuote = 0;
StringBuilder lineToWrite = new StringBuilder();
foreach (var s in tmpArr)
{
if (s.Contains("\""))
inQuote++;
switch (inQuote)
{
case 1:
//Begin quoted text
lineToWrite.Append(lineToWrite.Length > 0
? newDelim + s.Replace("\"", "")
: s.Replace("\"", ""));
if (s.Length > 4 && s.Substring(0, 2) == "\"\"" && s.Substring(s.Length - 2, 2) != "\"\"")
{
//if string has two quotes at the beginning and is > 4 characters and the last two characters are NOT quotes,
//inquote needs to be incremented.
inQuote++;
}
else if ((s.Substring(0, 1) == "\"" && s.Substring(s.Length - 1, 1) == "\"" &&
s.Length > 1) || (s.Count(x => x == '\"') % 2 == 0))
{
//if string has more than one character and both begins and ends with a quote, then it's ok and counter should be reset.
//if string has an EVEN number of quotes, it should be ok and counter should be reset.
inQuote = 0;
}
else
{
inQuote++;
}
break;
case 2:
//text between the quotes
//If we are here the origDelim value was found between the quotes
//include origDelim so there is no data loss.
//Example quoted text: "Dr. Mario, Sr, MD";
// ", Sr" would be handled here
// ", MD" would be handled in case 3 end of quoted text.
lineToWrite.Append(origDelim + s);
break;
case 3:
//End quoted text
//If we are here the origDelim value was found between the quotes
//and we are at the end of the quoted text
//include origDelim so there is no data loss.
//Example quoted text: "Dr. Mario, MD"
// ", MD" would be handled here.
lineToWrite.Append(origDelim + s.Replace("\"", ""));
inQuote = 0;
break;
default:
lineToWrite.Append(lineToWrite.Length > 0 ? newDelim + s : s);
break;
}
}
if (lineToWrite.Length > 0)
{
retStr = lineToWrite.ToString();
retArr = tmpLn.Split(new[] {newDelim}, StringSplitOptions.None);
}
}
}

Matching 2 strings in C#

I have 2 strings. These 2 strings can differ in size. I want to look at these 2 strings finding matching sequences. Once I find a change I want to print that word in Capital and then continue on in my string until I find another change and so on. I'm not sure how I would go about this I tried looking at words as a whole but I'm having issues with that. Basically I will have 2 string something like this string one="This is a new value" and string two= "This This is a new also brand value". I want go though each string from the start and find the matching sequences e.g. "This is" stop at string realise it has changed as string was added change it to upper case and then carry on. Expected output ="THIS this is a new ALSO BRAND value "
Some code I was trying. I don't think this is the right approach.
static void Main(string[] args)
{
string one = "This is a new value";
string two = "This This is a new also brand value";
var coll = two.Split(' ').Select(p => one.Contains(p) ? p : p.ToUpperInvariant());
Console.WriteLine(string.Join(" ", coll));
Console.ReadKey();
}
Is this what you're looking for? The description isn't fantastic, but judging by the answers this seems to be in the same ballpark, and it uses LINQ for less code and complication.
class Program
{
static void Main(string[] args)
{
string one = "This is text one";
string two = "This is string text two not string one";
var coll = two.Split(' ').Select(p => one.Contains(p) ? p : p.ToUpperInvariant());
Console.WriteLine(string.Join(" ", coll)); // This is STRING text TWO NOT STRING one
Console.ReadKey();
}
}
You can break this out to a separate method and pass your variables in as parameters.
You can convert string to char array and compare chars one by one. You can use the following code i guess.
string one = "this is string one";
string two = "this is string one or two";
char[] oneChar = one.ToCharArray();
char[] twoChar = two.ToCharArray();
int index = 0;
List<char> Diff = new List<char>();
if (oneChar.Length > twoChar.Length)
{
foreach (char item in twoChar)
{
if (item != oneChar[index])
Diff.Add(item);
index++;
}
for (int i = index; i < oneChar.Length; i++)
{
Diff.Add(oneChar[i]);
}
}
else if (oneChar.Length < twoChar.Length)
{
foreach (char item in oneChar)
{
if (item != twoChar[index])
Diff.Add(twoChar[index]);
index++;
}
for (int i = index; i < twoChar.Length; i++)
{
Diff.Add(twoChar[i]);
}
}
else//equal length
{
foreach (char item in twoChar)
{
if (item != oneChar[index])
Diff.Add(item);
}
}
Console.WriteLine(Diff.ToArray());//" or two"
Is that what you need? (Updated)
var value1 = "This is a new Value";
var value2 = "This is also a new value";
var separators = new[] { " " };
var value1Split = value1.Split(separators, StringSplitOptions.None);
var value2Split = value2.Split(separators, StringSplitOptions.None);
var result = new List<string>();
var i = 0;
var j = 0;
while (i < value1Split.Length && j < value2Split.Length)
{
if (value1Split[i].Equals(value2Split[j], StringComparison.OrdinalIgnoreCase))
{
result.Add(value2Split[j]);
i++;
j++;
}
else
{
result.Add(value2Split[j].ToUpper());
j++;
}
}
Console.WriteLine(string.Join(" ", result));
Console.ReadKey();
Note that if for value1="This is a new Value" and value2="This is also a new value" output should be "This is ALSO a new value" than for value1="This is text one" and value2="This is string text two not string one" output will be "This is STRING text TWO NOT STRING one", not "This is STRING TEXT TWO NOT STRING ONE" as you mentioned before.

How to call function over

I have made a function which can replace the position of the chars if they are standing in my list
Code:
public string NoSimilarChar(string password)
{
var listOfSimilarCharacters = new Dictionary<string, string>();
listOfSimilarCharacters.Add("l", "i");
listOfSimilarCharacters.Add("1", "i");
listOfSimilarCharacters.Add("O", "0");
// Iterate through each character
for (int i = 0; i < password.Length; i++)
{
var currentCharacter = password[i].ToString();
// check if the current char exists in either the key or the value of the list of similar characters
if (listOfSimilarCharacters.Keys.Contains(currentCharacter) || listOfSimilarCharacters.Values.Contains(currentCharacter))
{
currentCharacter = currentCharacter.Remove(currentCharacter.Length - 1, 1) + ",";
}
}
return password;
}
Now i want to know how to load the function NoSimilarChar over when the characters is remove
i thought something like this:
if (listOfSimilarCharacters.Keys.Contains(currentCharacter) || listOfSimilarCharacters.Values.Contains(currentCharacter))
{
currentCharacter = currentCharacter.Remove(currentCharacter.Length - 1, 1) + ",";
NoSimilarChar(password);
}
but i think this is not good because he then stays in a loop.
///for replacing
foreach (KeyValuePair<string, string> item in listOfSimilarCharacters)
{
password = password.Replace(item.Key, item.Value);
}
///for removing
foreach (KeyValuePair<string, string> item in listOfSimilarCharacters)
{
if (password.IndexOf(item.Key) >= 0)
password = password.Remove(password.IndexOf(item.Key), 1);
}
try this simpler one
var charsThatCannotbeinUserPwd = new[] {'1', 'l', 'O', '0', 'i'};
// Iterate through each character
var builder = new StringBuilder();
for (int i = 0; i < password.Length; i++)
{
var currentCharacter = password[i];
if (!charsThatCannotbeinUserPwd.Any(x => x.Equals(currentCharacter)))
builder.Append(currentCharacter);
}
return builder.ToString();
It looks like you want to remove a set of characters from you password. If that is the case then you don't need to use a Dictionary. A Dictionary would make more sense if you wanted to replace one character with another. Additionally you do not need to use recursion here. I believe all you need is an array of the characters you want to remove and a simple loop to remove them.
public string NoSimilarChar(string password)
{
string[] charsToRemove = new string[] { "l", "i", "1", "0", "O" }
foreach (string charToRemove in charsToRemove)
{
password = password.Replace(charToRemove, "");
}
return password;
}
FYI: I've defined the array of characters as strings because you will want to replace the character with an empty string and there is no empty character.

Comparing two RichTextBoxes?

I'm comparing richTextBox1 and richTextBox2 word by word.
// collect words from ritchtextbox1
String[] test = richtextbox1.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
// find each word test to richtextbox2
// if it is found then change back color of particular word to green of the
// else change back color of particular word to red in richtextbox1
test = richtextbox2.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
// find each word in test to richtextbox1
// if it is found then change back color of particular word to green of the
// else change back color of particular word to red in richtextbox2
can any one help me in code i'm little bit poor in syntax.
im taking reference of mateusz code
String[] test = richtextbox1.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
String[] test2 = richtextbox2.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
bool wordNotFound=false;
for (int i=0;i<test.lenght;i++)
for (int j=0;j<test2.length;j++){
if (test[i].equals(test2[j])){
wordNotFound=true
break;
}
else wordNotFound=true;
}
//// here i need the to change particular word back color not entire ritchtextbox
if (wordNotFound) richTextBox1.BackColor = Color.Red;
else richTextBox1.BackColor = Color.Green;
im not comparing two text boxes im validating each word which is exist in both side or not. just like spell check taking dictionary as one richtextbox1. spell check [valid word] in richtextbox2. vice versa...
var validWords = new HashSet<string>(new string[] { "a","c","e" });
string[] wordsToCheck = new string[] { "a", "b", "c", "d", "e" };
var result = wordsToCheck.Select(w => new
{
Word = w,
IsValid = validWords.Contains(w)
})
.ToList();
If you are only interested in whether all words are valid or not, you can simple check it by
var isOK = wordsToCheck.All(w => validWords.Contains(w));
PS: Of course, new string[]{}s should be replaced with rtb.Split(....) *
If the words would be in the same order why bother with splitting at all?
If it will be ok, I'd do:
if (richtexbox1.text.equals(richtexbox1.text)){
richTextBox1.BackColor = Color.Green;
} else {
richTextBox1.BackColor = Color.Red;
}
If not, and you want to find if both text boxes contain same word but in different order then:
String[] test = richtextbox1.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
String[] test2 = richtextbox2.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
bool wordNotFound=false;
for (int i=0;i<test.lenght;i++)
for (int j=0;j<test2.length;j++){
if (test[i].equals(test2[j])){
wordNotFound=false;
break;
}
else wordNotFound=true;
}
if (wordNotFound) richTextBox1.BackColor = Color.Red;
else richTextBox1.BackColor = Color.Green;
String[] test = richtextbox1.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
String[] test2 = richtextbox2.text.Split(" ", StringSplitOptions.RemoveEmptyEntries);
is giving error;
Error 1 The best overloaded method match for 'string.Split(string[],
System.StringSplitOptions)' has some invalid
arguments C:\Users\Saad\Documents\Visual Studio
2012\Projects\WindowsFormsApplication5\WindowsFormsApplication5\Form1.cs 60 29 WindowsFormsApplication5
Error 2 Argument 1: cannot convert from 'string' to
'string[]' C:\Users\Saad\Documents\Visual Studio
2012\Projects\WindowsFormsApplication5\WindowsFormsApplication5\Form1.cs 60 53 WindowsFormsApplication5
You could compare each word in textbox1 with textbox2
for(int i = 0; i < stringarray1.length; i++)
{
for(int j = 0; j < stringarray2.length; j++)
{
if(stringarray1[i] == stringarray2[j])
// we have a match
}
}

Categories