c# check textbox for unique values - c#

I have a textbox where user inputs values, each one in a new row, now i want to check if those input values are unique, but looks like it does not work if duplicated value is a last value, don't know why. Any tips?
Lets say it is:
1
2
3
3
It will not work, but
1
2
3
3
5
Will work and show an error as duplicate
Here is a code i use:
First I split textbox into array of strings
string[] linesValues = textBoxValues.Text.Split(new Char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
then check for duplicates and show error
if (linesValues.Distinct().Count() != linesValues.Count()) { MessageBox.Show("Question values must be unique!", "Duplicated values found", MessageBoxButtons.OK, MessageBoxIcon.Error); return; }

I suggest processing the values: removing empty / all whitespaces strings, leading and trailing spaces at least (note, that "3 " != " 3" != "3"):
new Char[] { '\n', '\r' } note \r can appear as a new line; let's be on the safer side of the road
.Where(item => !string.IsNullOrWhiteSpace(item)) we don't want all whitespaces line (empty lines included) like " "
item => item.Trim() questions processing; let "3" be equal to "3 "
Code:
string[] linesValues = textBoxValues
.Text
.Split(new Char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)
.Where(item => !string.IsNullOrWhiteSpace(item))
.Select(item => item.Trim())
.ToArray();
and then check as you do
using System.Linq;
...
if (linesValues.Distinct().Count() != linesValues.Count()) {
MessageBox.Show("Question values must be unique!",
"Duplicated values found",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}

private void button1_Click(object sender, EventArgs e)
{
int[] linesValues = new int[] { 1, 2, 3, 4, 1 };
if (AnyDuplicate(linesValues))
{
MessageBox.Show("Question values must be unique!", "Duplicated values found", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private bool AnyDuplicate(int[] numbers)
{
for (int i = 0; i < numbers.Length; i++)
{
for (int j = i + 1; j < numbers.Length; j++)
{
if (numbers[i] == numbers[j])
{
return true;
}
}
}
return false;
}

Related

Split a string if delimiter is between single quotes [duplicate]

This question already has answers here:
How to split csv whose columns may contain comma
(9 answers)
Closed 4 years ago.
I have the following comma-separated string that I need to split. The problem is that some of the content is within quotes and contains commas that shouldn't be used in the split.
String:
111,222,"33,44,55",666,"77,88","99"
I want the output:
111
222
33,44,55
666
77,88
99
I have tried this:
(?:,?)((?<=")[^"]+(?=")|[^",]+)
But it reads the comma between "77,88","99" as a hit and I get the following output:
111
222
33,44,55
666
77,88
,
99
Depending on your needs you may not be able to use a csv parser, and may in fact want to re-invent the wheel!!
You can do so with some simple regex
(?:^|,)(\"(?:[^\"]+|\"\")*\"|[^,]*)
This will do the following:
(?:^|,) = Match expression "Beginning of line or string ,"
(\"(?:[^\"]+|\"\")*\"|[^,]*) = A numbered capture group, this will select between 2 alternatives:
stuff in quotes
stuff between commas
This should give you the output you are looking for.
Example code in C#
static Regex csvSplit = new Regex("(?:^|,)(\"(?:[^\"]+|\"\")*\"|[^,]*)", RegexOptions.Compiled);
public static string[] SplitCSV(string input)
{
List<string> list = new List<string>();
string curr = null;
foreach (Match match in csvSplit.Matches(input))
{
curr = match.Value;
if (0 == curr.Length)
{
list.Add("");
}
list.Add(curr.TrimStart(','));
}
return list.ToArray();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine(SplitCSV("111,222,\"33,44,55\",666,\"77,88\",\"99\""));
}
Warning As per #MrE's comment - if a rogue new line character appears in a badly formed csv file and you end up with an uneven ("string) you'll get catastrophic backtracking (https://www.regular-expressions.info/catastrophic.html) in your regex and your system will likely crash (like our production system did). Can easily be replicated in Visual Studio and as I've discovered will crash it. A simple try/catch will not trap this issue either.
You should use:
(?:^|,)(\"(?:[^\"])*\"|[^,]*)
instead
Fast and easy:
public static string[] SplitCsv(string line)
{
List<string> result = new List<string>();
StringBuilder currentStr = new StringBuilder("");
bool inQuotes = false;
for (int i = 0; i < line.Length; i++) // For each character
{
if (line[i] == '\"') // Quotes are closing or opening
inQuotes = !inQuotes;
else if (line[i] == ',') // Comma
{
if (!inQuotes) // If not in quotes, end of current string, add it to result
{
result.Add(currentStr.ToString());
currentStr.Clear();
}
else
currentStr.Append(line[i]); // If in quotes, just add it
}
else // Add any other character to current string
currentStr.Append(line[i]);
}
result.Add(currentStr.ToString());
return result.ToArray(); // Return array of all strings
}
With this string as input :
111,222,"33,44,55",666,"77,88","99"
It will return :
111
222
33,44,55
666
77,88
99
i really like jimplode's answer, but I think a version with yield return is a little bit more useful, so here it is:
public IEnumerable<string> SplitCSV(string input)
{
Regex csvSplit = new Regex("(?:^|,)(\"(?:[^\"]+|\"\")*\"|[^,]*)", RegexOptions.Compiled);
foreach (Match match in csvSplit.Matches(input))
{
yield return match.Value.TrimStart(',');
}
}
Maybe it's even more useful to have it like an extension method:
public static class StringHelper
{
public static IEnumerable<string> SplitCSV(this string input)
{
Regex csvSplit = new Regex("(?:^|,)(\"(?:[^\"]+|\"\")*\"|[^,]*)", RegexOptions.Compiled);
foreach (Match match in csvSplit.Matches(input))
{
yield return match.Value.TrimStart(',');
}
}
}
This regular expression works without the need to loop through values and TrimStart(','), like in the accepted answer:
((?<=\")[^\"]*(?=\"(,|$)+)|(?<=,|^)[^,\"]*(?=,|$))
Here is the implementation in C#:
string values = "111,222,\"33,44,55\",666,\"77,88\",\"99\"";
MatchCollection matches = new Regex("((?<=\")[^\"]*(?=\"(,|$)+)|(?<=,|^)[^,\"]*(?=,|$))").Matches(values);
foreach (var match in matches)
{
Console.WriteLine(match);
}
Outputs
111
222
33,44,55
666
77,88
99
None of these answers work when the string has a comma inside quotes, as in "value, 1", or escaped double-quotes, as in "value ""1""", which are valid CSV that should be parsed as value, 1 and value "1", respectively.
This will also work with the tab-delimited format if you pass in a tab instead of a comma as your delimiter.
public static IEnumerable<string> SplitRow(string row, char delimiter = ',')
{
var currentString = new StringBuilder();
var inQuotes = false;
var quoteIsEscaped = false; //Store when a quote has been escaped.
row = string.Format("{0}{1}", row, delimiter); //We add new cells at the delimiter, so append one for the parser.
foreach (var character in row.Select((val, index) => new {val, index}))
{
if (character.val == delimiter) //We hit a delimiter character...
{
if (!inQuotes) //Are we inside quotes? If not, we've hit the end of a cell value.
{
Console.WriteLine(currentString);
yield return currentString.ToString();
currentString.Clear();
}
else
{
currentString.Append(character.val);
}
} else {
if (character.val != ' ')
{
if(character.val == '"') //If we've hit a quote character...
{
if(character.val == '\"' && inQuotes) //Does it appear to be a closing quote?
{
if (row[character.index + 1] == character.val) //If the character afterwards is also a quote, this is to escape that (not a closing quote).
{
quoteIsEscaped = true; //Flag that we are escaped for the next character. Don't add the escaping quote.
}
else if (quoteIsEscaped)
{
quoteIsEscaped = false; //This is an escaped quote. Add it and revert quoteIsEscaped to false.
currentString.Append(character.val);
}
else
{
inQuotes = false;
}
}
else
{
if (!inQuotes)
{
inQuotes = true;
}
else
{
currentString.Append(character.val); //...It's a quote inside a quote.
}
}
}
else
{
currentString.Append(character.val);
}
}
else
{
if (!string.IsNullOrWhiteSpace(currentString.ToString())) //Append only if not new cell
{
currentString.Append(character.val);
}
}
}
}
}
With minor updates to the function provided by "Chad Hedgcock".
Updates are on:
Line 26: character.val == '\"' - This can never be true due to the check made on Line 24. i.e. character.val == '"'
Line 28: if (row[character.index + 1] == character.val) added !quoteIsEscaped to escape 3 consecutive quotes.
public static IEnumerable<string> SplitRow(string row, char delimiter = ',')
{
var currentString = new StringBuilder();
var inQuotes = false;
var quoteIsEscaped = false; //Store when a quote has been escaped.
row = string.Format("{0}{1}", row, delimiter); //We add new cells at the delimiter, so append one for the parser.
foreach (var character in row.Select((val, index) => new {val, index}))
{
if (character.val == delimiter) //We hit a delimiter character...
{
if (!inQuotes) //Are we inside quotes? If not, we've hit the end of a cell value.
{
//Console.WriteLine(currentString);
yield return currentString.ToString();
currentString.Clear();
}
else
{
currentString.Append(character.val);
}
} else {
if (character.val != ' ')
{
if(character.val == '"') //If we've hit a quote character...
{
if(character.val == '"' && inQuotes) //Does it appear to be a closing quote?
{
if (row[character.index + 1] == character.val && !quoteIsEscaped) //If the character afterwards is also a quote, this is to escape that (not a closing quote).
{
quoteIsEscaped = true; //Flag that we are escaped for the next character. Don't add the escaping quote.
}
else if (quoteIsEscaped)
{
quoteIsEscaped = false; //This is an escaped quote. Add it and revert quoteIsEscaped to false.
currentString.Append(character.val);
}
else
{
inQuotes = false;
}
}
else
{
if (!inQuotes)
{
inQuotes = true;
}
else
{
currentString.Append(character.val); //...It's a quote inside a quote.
}
}
}
else
{
currentString.Append(character.val);
}
}
else
{
if (!string.IsNullOrWhiteSpace(currentString.ToString())) //Append only if not new cell
{
currentString.Append(character.val);
}
}
}
}
}
For Jay's answer, if you use a 2nd boolean then you can have nested double-quotes inside single-quotes and vice-versa.
private string[] splitString(string stringToSplit)
{
char[] characters = stringToSplit.ToCharArray();
List<string> returnValueList = new List<string>();
string tempString = "";
bool blockUntilEndQuote = false;
bool blockUntilEndQuote2 = false;
int characterCount = 0;
foreach (char character in characters)
{
characterCount = characterCount + 1;
if (character == '"' && !blockUntilEndQuote2)
{
if (blockUntilEndQuote == false)
{
blockUntilEndQuote = true;
}
else if (blockUntilEndQuote == true)
{
blockUntilEndQuote = false;
}
}
if (character == '\'' && !blockUntilEndQuote)
{
if (blockUntilEndQuote2 == false)
{
blockUntilEndQuote2 = true;
}
else if (blockUntilEndQuote2 == true)
{
blockUntilEndQuote2 = false;
}
}
if (character != ',')
{
tempString = tempString + character;
}
else if (character == ',' && (blockUntilEndQuote == true || blockUntilEndQuote2 == true))
{
tempString = tempString + character;
}
else
{
returnValueList.Add(tempString);
tempString = "";
}
if (characterCount == characters.Length)
{
returnValueList.Add(tempString);
tempString = "";
}
}
string[] returnValue = returnValueList.ToArray();
return returnValue;
}
The original version
Currently I use the following regex:
public static Regex regexCSVSplit = new Regex(#"(?x:(
(?<FULL>
(^|[,;\t\r\n])\s*
( (?<QUODAT> (?<QUO>[""'])(?<DAT>([^,;\t\r\n]|(?<!\k<QUO>\s*)[,;\t\r\n])*)\k<QUO>) |
(?<QUODAT> (?<DAT> [^""',;\s\r\n]* )) )
(?=\s*([,;\t\r\n]|$))
) |
(?<FULL>
(^|[\s\t\r\n])
( (?<QUODAT> (?<QUO>[""'])(?<DAT> [^""',;\s\t\r\n]* )\k<QUO>) |
(?<QUODAT> (?<DAT> [^""',;\s\t\r\n]* )) )
(?=[,;\s\t\r\n]|$)
)
))", RegexOptions.Compiled);
This solution can handle pretty chaotic cases too like below:
This is how to feed the result into an array:
var data = regexCSVSplit.Matches(line_to_process).Cast<Match>().
Select(x => x.Groups["DAT"].Value).ToArray();
See this example in action HERE
Note: The regular expression contains two set of <FULL> block and each of them contains two <QUODAT> block separated by "or" (|). Depending on your task you may only need one of them.
Note: That this regular expression gives us one string array, and works on single line with or without <carrier return> and/or <line feed>.
Simplified version
The following regular expression will already cover many complex cases:
public static Regex regexCSVSplit = new Regex(#"(?x:(
(?<FULL>
(^|[,;\t\r\n])\s*
(?<QUODAT> (?<QUO>[""'])(?<DAT>([^,;\t\r\n]|(?<!\k<QUO>\s*)[,;\t\r\n])*)\k<QUO>)
(?=\s*([,;\t\r\n]|$))
)
))", RegexOptions.Compiled);
See this example in action: HERE
It can process complex, easy and empty items too:
This is how to feed the result into an array:
var data = regexCSVSplit.Matches(line_to_process).Cast<Match>().
Select(x => x.Groups["DAT"].Value).ToArray();
The main rule here is that every item may contain anything but the <quotation mark><separators><comma> sequence AND each item shall being and end with the same <quotation mark>.
<quotation mark>: <">, <'>
<comma>: <,>, <;>, <tab>, <carrier return>, <line feed>
Edit notes: I added some more explanation to make it easier to understand and replaces the text "CO" with "QUO".
Try this:
string s = #"111,222,""33,44,55"",666,""77,88"",""99""";
List<string> result = new List<string>();
var splitted = s.Split('"').ToList<string>();
splitted.RemoveAll(x => x == ",");
foreach (var it in splitted)
{
if (it.StartsWith(",") || it.EndsWith(","))
{
var tmp = it.TrimEnd(',').TrimStart(',');
result.AddRange(tmp.Split(','));
}
else
{
if(!string.IsNullOrEmpty(it)) result.Add(it);
}
}
//Results:
foreach (var it in result)
{
Console.WriteLine(it);
}
I know I'm a bit late to this, but for searches, here is how I did what you are asking about in C sharp
private string[] splitString(string stringToSplit)
{
char[] characters = stringToSplit.ToCharArray();
List<string> returnValueList = new List<string>();
string tempString = "";
bool blockUntilEndQuote = false;
int characterCount = 0;
foreach (char character in characters)
{
characterCount = characterCount + 1;
if (character == '"')
{
if (blockUntilEndQuote == false)
{
blockUntilEndQuote = true;
}
else if (blockUntilEndQuote == true)
{
blockUntilEndQuote = false;
}
}
if (character != ',')
{
tempString = tempString + character;
}
else if (character == ',' && blockUntilEndQuote == true)
{
tempString = tempString + character;
}
else
{
returnValueList.Add(tempString);
tempString = "";
}
if (characterCount == characters.Length)
{
returnValueList.Add(tempString);
tempString = "";
}
}
string[] returnValue = returnValueList.ToArray();
return returnValue;
}
Don't reinvent a CSV parser, try FileHelpers.
I needed something a little more robust, so I took from here and created this... This solution is a little less elegant and a little more verbose, but in my testing (with a 1,000,000 row sample), I found this to be 2 to 3 times faster. Plus it handles non-escaped, embedded quotes. I used string delimiter and qualifiers instead of chars because of the requirements of my solution. I found it more difficult than I expected to find a good, generic CSV parser so I hope this parsing algorithm can help someone.
public static string[] SplitRow(string record, string delimiter, string qualifier, bool trimData)
{
// In-Line for example, but I implemented as string extender in production code
Func <string, int, int> IndexOfNextNonWhiteSpaceChar = delegate (string source, int startIndex)
{
if (startIndex >= 0)
{
if (source != null)
{
for (int i = startIndex; i < source.Length; i++)
{
if (!char.IsWhiteSpace(source[i]))
{
return i;
}
}
}
}
return -1;
};
var results = new List<string>();
var result = new StringBuilder();
var inQualifier = false;
var inField = false;
// We add new columns at the delimiter, so append one for the parser.
var row = $"{record}{delimiter}";
for (var idx = 0; idx < row.Length; idx++)
{
// A delimiter character...
if (row[idx]== delimiter[0])
{
// Are we inside qualifier? If not, we've hit the end of a column value.
if (!inQualifier)
{
results.Add(trimData ? result.ToString().Trim() : result.ToString());
result.Clear();
inField = false;
}
else
{
result.Append(row[idx]);
}
}
// NOT a delimiter character...
else
{
// ...Not a space character
if (row[idx] != ' ')
{
// A qualifier character...
if (row[idx] == qualifier[0])
{
// Qualifier is closing qualifier...
if (inQualifier && row[IndexOfNextNonWhiteSpaceChar(row, idx + 1)] == delimiter[0])
{
inQualifier = false;
continue;
}
else
{
// ...Qualifier is opening qualifier
if (!inQualifier)
{
inQualifier = true;
}
// ...It's a qualifier inside a qualifier.
else
{
inField = true;
result.Append(row[idx]);
}
}
}
// Not a qualifier character...
else
{
result.Append(row[idx]);
inField = true;
}
}
// ...A space character
else
{
if (inQualifier || inField)
{
result.Append(row[idx]);
}
}
}
}
return results.ToArray<string>();
}
Some test code:
//var input = "111,222,\"33,44,55\",666,\"77,88\",\"99\"";
var input =
"111, 222, \"99\",\"33,44,55\" , \"666 \"mark of a man\"\", \" spaces \"77,88\" \"";
Console.WriteLine("Split with trim");
Console.WriteLine("---------------");
var result = SplitRow(input, ",", "\"", true);
foreach (var r in result)
{
Console.WriteLine(r);
}
Console.WriteLine("");
// Split 2
Console.WriteLine("Split with no trim");
Console.WriteLine("------------------");
var result2 = SplitRow(input, ",", "\"", false);
foreach (var r in result2)
{
Console.WriteLine(r);
}
Console.WriteLine("");
// Time Trial 1
Console.WriteLine("Experimental Process (1,000,000) iterations");
Console.WriteLine("-------------------------------------------");
watch = Stopwatch.StartNew();
for (var i = 0; i < 1000000; i++)
{
var x1 = SplitRow(input, ",", "\"", false);
}
watch.Stop();
elapsedMs = watch.ElapsedMilliseconds;
Console.WriteLine($"Total Process Time: {string.Format("{0:0.###}", elapsedMs / 1000.0)} Seconds");
Console.WriteLine("");
Results
Split with trim
---------------
111
222
99
33,44,55
666 "mark of a man"
spaces "77,88"
Split with no trim
------------------
111
222
99
33,44,55
666 "mark of a man"
spaces "77,88"
Original Process (1,000,000) iterations
-------------------------------
Total Process Time: 7.538 Seconds
Experimental Process (1,000,000) iterations
--------------------------------------------
Total Process Time: 3.363 Seconds
I once had to do something similar and in the end I got stuck with Regular Expressions. The inability for Regex to have state makes it pretty tricky - I just ended up writing a simple little parser.
If you're doing CSV parsing you should just stick to using a CSV parser - don't reinvent the wheel.
Here is my fastest implementation based upon string raw pointer manipulation:
string[] FastSplit(string sText, char? cSeparator = null, char? cQuotes = null)
{
string[] oTokens;
if (null == cSeparator)
{
cSeparator = DEFAULT_PARSEFIELDS_SEPARATOR;
}
if (null == cQuotes)
{
cQuotes = DEFAULT_PARSEFIELDS_QUOTE;
}
unsafe
{
fixed (char* lpText = sText)
{
#region Fast array estimatation
char* lpCurrent = lpText;
int nEstimatedSize = 0;
while (0 != *lpCurrent)
{
if (cSeparator == *lpCurrent)
{
nEstimatedSize++;
}
lpCurrent++;
}
nEstimatedSize++; // Add EOL char(s)
string[] oEstimatedTokens = new string[nEstimatedSize];
#endregion
#region Parsing
char[] oBuffer = new char[sText.Length];
int nIndex = 0;
int nTokens = 0;
lpCurrent = lpText;
while (0 != *lpCurrent)
{
if (cQuotes == *lpCurrent)
{
// Quotes parsing
lpCurrent++; // Skip quote
nIndex = 0; // Reset buffer
while (
(0 != *lpCurrent)
&& (cQuotes != *lpCurrent)
)
{
oBuffer[nIndex] = *lpCurrent; // Store char
lpCurrent++; // Move source cursor
nIndex++; // Move target cursor
}
}
else if (cSeparator == *lpCurrent)
{
// Separator char parsing
oEstimatedTokens[nTokens++] = new string(oBuffer, 0, nIndex); // Store token
nIndex = 0; // Skip separator and Reset buffer
}
else
{
// Content parsing
oBuffer[nIndex] = *lpCurrent; // Store char
nIndex++; // Move target cursor
}
lpCurrent++; // Move source cursor
}
// Recover pending buffer
if (nIndex > 0)
{
// Store token
oEstimatedTokens[nTokens++] = new string(oBuffer, 0, nIndex);
}
// Build final tokens list
if (nTokens == nEstimatedSize)
{
oTokens = oEstimatedTokens;
}
else
{
oTokens = new string[nTokens];
Array.Copy(oEstimatedTokens, 0, oTokens, 0, nTokens);
}
#endregion
}
}
// Epilogue
return oTokens;
}
Try this
private string[] GetCommaSeperatedWords(string sep, string line)
{
List<string> list = new List<string>();
StringBuilder word = new StringBuilder();
int doubleQuoteCount = 0;
for (int i = 0; i < line.Length; i++)
{
string chr = line[i].ToString();
if (chr == "\"")
{
if (doubleQuoteCount == 0)
doubleQuoteCount++;
else
doubleQuoteCount--;
continue;
}
if (chr == sep && doubleQuoteCount == 0)
{
list.Add(word.ToString());
word = new StringBuilder();
continue;
}
word.Append(chr);
}
list.Add(word.ToString());
return list.ToArray();
}
This is Chad's answer rewritten with state based logic. His answered failed for me when it came across """BRAD""" as a field. That should return "BRAD" but it just ate up all the remaining fields. When I tried to debug it I just ended up rewriting it as state based logic:
enum SplitState { s_begin, s_infield, s_inquotefield, s_foundquoteinfield };
public static IEnumerable<string> SplitRow(string row, char delimiter = ',')
{
var currentString = new StringBuilder();
SplitState state = SplitState.s_begin;
row = string.Format("{0}{1}", row, delimiter); //We add new cells at the delimiter, so append one for the parser.
foreach (var character in row.Select((val, index) => new { val, index }))
{
//Console.WriteLine("character = " + character.val + " state = " + state);
switch (state)
{
case SplitState.s_begin:
if (character.val == delimiter)
{
/* empty field */
yield return currentString.ToString();
currentString.Clear();
} else if (character.val == '"')
{
state = SplitState.s_inquotefield;
} else
{
currentString.Append(character.val);
state = SplitState.s_infield;
}
break;
case SplitState.s_infield:
if (character.val == delimiter)
{
/* field with data */
yield return currentString.ToString();
state = SplitState.s_begin;
currentString.Clear();
} else
{
currentString.Append(character.val);
}
break;
case SplitState.s_inquotefield:
if (character.val == '"')
{
// could be end of field, or escaped quote.
state = SplitState.s_foundquoteinfield;
} else
{
currentString.Append(character.val);
}
break;
case SplitState.s_foundquoteinfield:
if (character.val == '"')
{
// found escaped quote.
currentString.Append(character.val);
state = SplitState.s_inquotefield;
}
else if (character.val == delimiter)
{
// must have been last quote so we must find delimiter
yield return currentString.ToString();
state = SplitState.s_begin;
currentString.Clear();
}
else
{
throw new Exception("Quoted field not terminated.");
}
break;
default:
throw new Exception("unknown state:" + state);
}
}
//Console.WriteLine("currentstring = " + currentString.ToString());
}
This is a lot more lines of code than the other solutions, but it is easy to modify to add edge cases.

Comparing array and get another array value on the selected array

Please help me. I'm stuck on my array case. I'm newbie on this. Espesially to get array more than 2 variables. I had already browsing into google but i didn't got what i want, and now I've got stuck on it :(
I have array like this
string[] receive = receiveattachment.Split(new char[] { ',' });//{1,0,1,0}
string[] display = isdisplaytotal.Split(new char[] { ',' });//{1,1,1,0}
string[] ccTemp = cc.Split(new char[] { ',' });//{a#gmail.com, b#gmail.com, c#gmail.com, d#gmail.com}
First of all i got the same value from receive and display by this
foreach (var receive_ in receive)
{
foreach (var display_ in display)
{
if (receive_ == display_)
{
//do something
}
}
}
then my problem is, how to get a#gmail.com, c#gmail.com ?
I tried like this
foreach (var receive_ in receive)
{
foreach (var display_ in display)
{
if (receive_ == display_)
{
string[] ccTemp = cc.Split(new char[] { ',' });
for (int i = 0; i < receive.Length; i++)
{
if (receive[i] == "1")
{
if (_ccIsReceiveAndDisplay.Trim() != "") _ccIsReceiveAndDisplay += ",";
_ccIsReceiveAndDisplay += ccTemp[i];
}
else
{
if (_ccIsReceiveAndDisplay.Trim() != "") _ccIsReceiveAndDisplay += ",";
_ccIsReceiveAndDisplay += ccTemp[i];
}
}
}
}
}
but it will got only receive = 1 value. not receive 1 and display =1
If all the arrays are the same length, use for and an index.
Like this:
for (var index=0; index<receive.length; index++)
if (receive[index] == "1" && display[index] == "1")
DoSomethingWithEmail( ccTemp[index] )
This is also faster, because it loops through the array only once, not once per element in the array.
As a bonus, get the emails the linq-way:
receive.Zip(display, (a,b) => new {A=a, B=b}).Zip(ccTemp, (ab,c) => new {use=ab.A=="1"&&ab.B=="1", email=c}).Where( x=> x.use ).Select( x => x.email)

Pig Latin Translator spitting out multiple lines? C#

So I have a Pig Latin Translator that supports multiple words. But whenever I enter some words (For this we'll just use "banana apple shears chocolate Theodore train" for example.) It will spit out the translated words correctly but it makes repeats! Here is my code:
namespace Pig_Latin_Translator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<string> vowels = new List<string>();
List<string> specials = new List<string>();
private void TranslateButton_Click(object sender, EventArgs e)
{
String[] parts = TranslateBox.Text.Split();
foreach (string s in specials)
{
if (TranslateBox.Text.Contains(s) || TranslateBox.Text == "\"")
{
TranslateOutput.Text = "";
MessageBox.Show("No Special Characters!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
break;
}
else
{
foreach (String part in parts)
{
foreach (String v in vowels)
{
if (part.Substring(0, 1) == v)
{
TranslateOutput.Text = TranslateOutput.Text + " " + part + "ay";
break;
}
else
{
if (part.Substring(0, 2) == "sh" || part.Substring(0, 2) == "ch" || part.Substring(0, 2) == "th" || part.Substring(0, 2) == "tr")
{
string SwitchP = part.Substring(2) + part.Substring(0, 2);
TranslateOutput.Text = TranslateOutput.Text + " " + SwitchP + "ay";
break;
}
else
{
string Switch = part.Substring(1) + part.Substring(0, 1);
TranslateOutput.Text = TranslateOutput.Text + " " + Switch + "ay";
break;
}
}
}
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
vowels.Add("a");
vowels.Add("e");
vowels.Add("i");
vowels.Add("o");
vowels.Add("u");
specials.Add("`");
specials.Add("1");
specials.Add("2");
specials.Add("3");
specials.Add("4");
specials.Add("5");
specials.Add("6");
specials.Add("7");
specials.Add("8");
specials.Add("9");
specials.Add("0");
specials.Add("-");
specials.Add("=");
specials.Add("[");
specials.Add("]");
specials.Add(#"\");
specials.Add(";");
specials.Add("'");
specials.Add(",");
specials.Add(".");
specials.Add("/");
specials.Add("~");
specials.Add("!");
specials.Add("#");
specials.Add("#");
specials.Add("$");
specials.Add("%");
specials.Add("^");
specials.Add("&");
specials.Add("*");
specials.Add("(");
specials.Add(")");
specials.Add("_");
specials.Add("+");
specials.Add("{");
specials.Add("}");
specials.Add("|");
specials.Add(":");
specials.Add("\"");
specials.Add("<");
specials.Add(">");
specials.Add("?");
}
private void AboutButton_Click(object sender, EventArgs e)
{
MessageBox.Show("Pig Latin is a fake language. It works by taking the first letter (Or two if it's a pair like 'th' or 'ch') and bringing it to the end, unless the first letter is a vowel. Then add 'ay' to the end. So 'bus' becomes 'usbay', 'thank' becomes 'ankthay' and 'apple' becomes 'appleay'.", "About:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
Which outputs if you typed in "banana apple shears chocolate Theodore train":
"ananabay appleay earsshay ocolatechay heodoreTay aintray" repeating over 10 times.
BTW: Sorry if you can't answer because I know there is LOTS of code. But it doesn't matter because the thing still is useful. It's just that it shouldn't happen and get on my nerves. And I know there is still many glitches and MUCH more to do but I want to get this resolved first.
You are nesting your code in two loops that it shouldn't be nested in
foreach (string s in specials)
and
foreach (String v in vowels)
Your break statements are getting you out of trouble for one, but not the other.
You can avoid these loops entirely is you use the .Any(...) predicate.
Here's what your code could look like:
private void TranslateButton_Click(object sender, EventArgs e)
{
TranslateOutput.Text = "";
if (specials.Any(s => TranslateBox.Text.Contains(s)))
{
MessageBox.Show("No Special Characters!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
String[] parts = TranslateBox.Text.Split();
foreach (var part in parts)
{
var index = 1;
if (vowels.Any(v => part.Substring(0, 1).ToLower() == v))
{
index = 0;
}
else if (new [] { "sh", "ch", "th", "tr", }.Contains(part.Substring(0, 2).ToLower()))
{
index = 2;
}
TranslateOutput.Text += " " + part.Substring(index) + part.Substring(0, index);
}
}
TranslateOutput.Text = TranslateOutput.Text.TrimEnd();
}
This brings it down to the one foreach loop that you actually need.
You can also get your code to initalize vowels and specials down to this:
vowels.AddRange("aeiou".Select(x => x.ToString()));
specials.AddRange(#"`1234567890-=[]\;',./~!##$%^&*()_+{}|:""<>?".Select(x => x.ToString()));
You are iterating through your words once for each special character. Your foreach to go through your words and translate is inside of your foreach to check to see if the textbox contains any special characters.
In otherwords, you are going to do your translation once per special character.
You'll want to move your foreach (String part in parts) out of your foreach (string s in specials)
You have a bit of a logic problem in your loops.
Your outer loop:
foreach( string s in specials ) {
...is looping through all 42 characters in your special characters list.
Your inner loop
foreach( String part in parts ) {
...is then executed 42 times. So for your six word example you're actually doing your pig latin conversion 252 times.
If you extract the inner loop from the outer, your results are better. Like this:
foreach( string s in specials ) {
if( TranslateBox.Text.Contains( s ) || TranslateBox.Text == "\"" ) {
TranslateOutput.Text = "";
MessageBox.Show( "No Special Characters!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning );
return;
}
}
String[] parts = TranslateBox.Text.Split();
foreach( String part in parts ) {
foreach( String v in vowels ) {
if( part.Substring( 0, 1 ) == v ) {
TranslateOutput.Text = TranslateOutput.Text + " " + part + "ay";
break;
}
else {
if( part.Substring( 0, 2 ) == "sh" || part.Substring( 0, 2 ) == "ch" || part.Substring( 0, 2 ) == "th" || part.Substring( 0, 2 ) == "tr" ) {
string SwitchP = part.Substring( 2 ) + part.Substring( 0, 2 );
TranslateOutput.Text = TranslateOutput.Text + " " + SwitchP + "ay";
break;
}
else {
string Switch = part.Substring( 1 ) + part.Substring( 0, 1 );
TranslateOutput.Text = TranslateOutput.Text + " " + Switch + "ay";
break;
}
}
}
}
A somewhat more concise implementation would be:
private void TranslateButton_Click( object sender, EventArgs e )
{
char[] specials = "`1234567890-=[]\";',./~!##$%^&*()_+{}|:\\<>?".ToArray();
char[] vowels = "aeiou".ToArray();
TranslateOutput.Text = String.Empty;
if( TranslateBox.Text.IndexOfAny( specials ) > -1 ) {
MessageBox.Show( "No Special Characters!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning );
return;
}
String[] parts = TranslateBox.Text.Split();
foreach( String part in parts ) {
int firstVowel = part.IndexOfAny( vowels );
if( firstVowel > 0 ) {
TranslateOutput.Text += part.Substring( firstVowel ) + part.Substring( 0, firstVowel ) + "ay ";
}
else {
TranslateOutput.Text += part + "ay ";
}
}
TranslateOutput.Text = TranslateOutput.Text.TrimEnd();
}
In this example, I create two character arrays for the specials and the vowels. I can then leverage the framework's IndexOfAny method to search for any of the characters in the array and return the index of the first occurrence. That will find the first special, if any, in the first loop and the first vowel in the second loop. Once I have that character index from the word I can parse the word into pig Latin. Note that I'm checking for zero as the vowel index since, in pig Latin a leading vowel stays where it is and the "ay" is just appended to the end of the word.

How can I delete the selected Lines in Multi line Text Box?

My code below here I used "SelectedLines" to find the current selected lines by user, AllLines to find the no of total lines in Multi line text box. in last for loop when i=1 it runs successfully but when i is +1 = 2 then it gives me error
Error : "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index?"
// Retrieve selected lines
List<string> SelectedLines = Regex.Split(txtNewURLs.SelectedText, #"\r\n").ToList();
// Check for nothing, Regex.Split returns empty string when no text is inputted
if (SelectedLines.Count == 1)
{
if (String.IsNullOrWhiteSpace(SelectedLines[0]))
{
SelectedLines.Remove("");
}
}
// Retrieve all lines from textbox
List<string> AllLines = Regex.Split(txtNewURLs.Text, #"\r\n").ToList();
// Check for nothing, Regex.Split returns empty string when no text is inputted
if (AllLines.Count == 1)
{
if (String.IsNullOrWhiteSpace(AllLines[0]))
{
AllLines.Remove("");
}
}
string SelectedMessage = "The following lines have been selected";
int numSelected = 0;
// Find all selected lines
foreach (string IndividualLine in AllLines)
{
if (SelectedLines.Any(a => a.Equals(IndividualLine)))
{
SelectedMessage += "\nLine #" + AllLines.FindIndex(a => a.Equals(IndividualLine));
// changing the status of the selected lene from 0 to 1
AddURL objAddURL = new AddURL();
objAddURL.Where.SURL.Value = IndividualLine;
objAddURL.Where.ILicenseID.Value = CommonMethods.iLicenseID;
objAddURL.Query.Load();
if (objAddURL.RowCount > 0)
{
AddURL objaddurl1 = new AddURL();
objaddurl1.LoadByPrimaryKey(objAddURL.IAddURLID);
if (objaddurl1.RowCount > 0)
{
objaddurl1.IStatus = 1;
objaddurl1.Save();
}
// AllLines.Remove(IndividualLine);
}
numSelected++;
}
}
// int[] lineNo = new int[AllLines.Count];
int linesNO = SelectedLines.Count;
for (int i = 1; i <= linesNO; i++)
{
SelectedLines.RemoveAt(i);
}
// MessageBox.Show((numSelected > 0) ? SelectedMessage : "No lines selected.");
Could any body please help me to solve this issue or suggest me new code?
Indices in c# are zero based.
for (int i = 0; i < linesNO; i++)
SelectedLines.RemoveAt(i);
But if you want to delete the selected lines from your textBox your code should rather look like
List<string> SelectedLines = new List<string> { "b", "c" };
textBox1.Lines = textBox1.Lines.ToList().Except(SelectedLines).ToArray();

Regex behaving strangely .net

I have some code which reads every row of a CSV file and if the value doesn't match the correct value, it will add it to the error list which is returned to the users screen. The problem I am having is with the regex itself.
protected void ReadData(string filePath, bool upload)
{
StringBuilder sb = new StringBuilder();
#region upload
if (upload == true) // CSV file upload chosen
{
using (CsvReader csv = new CsvReader(new StreamReader(filePath), true)) // Cache CSV file to memory
{
int fieldCount = csv.FieldCount; // Total number of fields per row
string[] headers = csv.GetFieldHeaders(); // Correct CSV headers stored in array
SortedList<int, string> errorList = new SortedList<int, string>(); // This list will contain error values
bool errorFlag = false;
int errorCount = 0;
// Check if headers are correct first before reading data
if (headers[0] != "first name" || headers[1] != "last name" || headers[2] != "job title" || headers[3] != "email address" || headers[4] != "telephone number" || headers[5] != "company" || headers[6] != "research manager" || headers[7] != "user card number")
{
sb.Append("Headers are incorrect");
}
else
{
while (csv.ReadNextRecord())
try
{
//Check csv obj data for valid values
for (int i = 0; i < fieldCount; i++)
{
if (i == 0 || i == 1) // FirstName and LastName
{
if (Regex.IsMatch(csv[i].ToString(), "[a-zA-Z]", RegexOptions.IgnoreCase)) //REGEX letters only min of 5 char max of 20
{
errorList.Add(errorCount, csv[i]);
errorCount += 1;
errorFlag = true;
string text = csv[i].ToString();
}
}
else if (i == 5) // Company name
{
string text = csv[i];
text.Replace("&", "and");
}
}
if (errorFlag == true)
{
sb.Append("<b>" + "Number of Error: " + errorCount + "</b>");
sb.Append("<ul>");
foreach (KeyValuePair<int, string> key in errorList)
{
sb.Append("<li>" + key.Value + "</li>");
}
}
else // All validation checks equaled to false. Create User
{
ORCLdap.CreateUserAccount(rootLDAPPath, svcUsername, svcPassword, csv[0], csv[1], csv[2], csv[3], csv[4], csv[5], csv[7]);
sb.Append("<b>New user data uploaded successfully</b>");
}
}// end of try
catch (Exception ex)
{
sb.Append(ex.ToString());
}
finally
{
lblMessage.Text = sb.ToString();
sb.Remove(0, sb.Length);
}
}
}
#endregion
The lblMessage.text contains this html:
Number of Error: 4
David1212
smith
Nick444
Gowdy333
When it should be 3 errors because smith doesnt contain a number.
Does anyone have suggestions for this?
You also have a logic error:
if (Regex.IsMatch(csv[i].ToString(), "[a-zA-Z]", RegexOptions.IgnoreCase)) //REGEX letters only min of 5 char max of 20
should be
if (!Regex.IsMatch(csv[i].ToString(), "^[a-zA-Z]+$", RegexOptions.IgnoreCase)) //REGEX letters only min of 5 char max of 20
because it is only an error if the name has other characters than [a-zA-Z] in it, right?
(and if you use RegexOptions.IgnoreCase you don't need [a-zA-Z], [a-z] would do)
You need to add word boundaries to your regex, or starting '^' and end '$'
i.e.
^[a-zA-Z]+$
http://regexr.com?3298g
Your current regex is incorrect, and will match any string which contains a-z or A-Z , any letter,at any position.
http://regexr.com?3298j

Categories

Resources