Duplicates using Arrays and TextFile - c#
I'm having an issue outputting my current code in Unity. I'm using an output text field to display the amount of duplicates per number.
Been browsing feeds and haven't gotten what I needed so here I am asking this now.
public int whatIndex,count;
public Text output;
public void Start()
{
string Random = "";
//reading the text file
string Duplicates = "duplicates.txt";
string Duplicates_Path = Application.dataPath + "/Text_Files/" + Duplicates;
string[] Numbers = File.ReadAllLines(Duplicates_Path);
foreach(string number in Numbers)
{
Random += number;
}
output.text = Random + "\n";
//array for text
for (whatIndex = 0; whatIndex < Duplicates.Length; whatIndex++)
{
Debug.Log(Numbers[whatIndex] + "\n");
Debug.Log("The number " + Numbers[whatIndex].ToString() + " appears " + count +
" times(s)");
}
}
As I understand you want to count occurrence for each number which is available in duplicate.txt files. Please find below code, i have tweak your code little bit e.g. file path and debug.log and remove unnecessary variables. you can see input here and output here:
public void Start()
{
Dictionary<int, int> numberCount = new Dictionary<int, int>();
//reading the text file
string Duplicates = "duplicates.txt";
string Duplicates_Path = Environment.CurrentDirectory + "\\Text_Files\\" + Duplicates;
string[] Numbers = File.ReadAllLines(Duplicates_Path);
foreach (string number in Numbers)
{
int temp = int.Parse(number);
if (numberCount.ContainsKey(temp))
{
numberCount[temp] = numberCount[temp] + 1;
}
else
{
numberCount[temp] = 1;
}
}
//array for text
foreach(KeyValuePair<int,int> item in numberCount)
{
Console.WriteLine("The number " + item.Key.ToString() + " appears " + item.Value.ToString() +
" times(s)");
}
}
I am not sure, what you want to achieve but I guess, there are some problems with your code (see after code).
Example Snippet:
First of all, you can try to use this code to get an idea about one solution to get the duplicates and the number of duplicates after reading the text file by using a Dictionary from System.Collections.Generic:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// String array with duplicates
string[] Numbers = {"1","1", "2", "6","1","7","1","7","8","3"};
Dictionary<string, int> KeyNumbersValueCount = new Dictionary<string, int>();
foreach(string number in Numbers)
{
if(KeyNumbersValueCount.ContainsKey(number))
KeyNumbersValueCount[number] += 1;
else
KeyNumbersValueCount.Add(number, 1);
}
foreach(var NumberAndCount in KeyNumbersValueCount)
Console.WriteLine("The number " + NumberAndCount.Key + " appears " +
NumberAndCount.Value + " times(s)");
}
}
running example code above
Open Issues with your code from the question:
Do you need count? It is initializied but never used
If you don't need "whatIndex", then you can also initialize it within the for loop:
for (int whatIndex = 0; whatIndex < Duplicates.Length; whatIndex++)
{
// do s.th.
}
You are trying to iterate over length of the string "Duplicates", which is "duplicates.txt" and therefore it has a length of 14. I guess you want to iterate over your strings in your file.
In your case, Random doesn't really have a function. You could also use File.ReadAllText instead of File.ReadAllLines and hand it over to output.text, if you only want to print it. See Microsoft Refs.
Related
how to escape a variable in c#
I hope the title is clear enough, but what I want is like this: string hello = "0012"; string escapedHello = "\u" + hello; The reason for this, is beacuse, the program is for printing labels on a brother ptouch printer, which have a template stored, and it can print the variables from the file, i will create with my program. My program works now, but not the "smartest" way. Right now it is a certain amount of length, so i append some spaces on the values, that don't live up the required length. The length of the value, is stored in hex, and right now, i Write the value length with: \u0004 I want to take the values i get via. my program, and get the length, and write it as hex, in the file, because then the length will be dymanic, and the text the printer prints, will be more enjoyable to read. Here is the code for my program: static void Main(string[] lines) { //Directory.SetCurrentDirectory(#"C:\HireLabel"); //string[] lines = File.ReadAllLines("var.txt"); string[] hexstrings = new string[lines.Length-1]; string[] replaceWith = { "Modelnavn1111111", "Variant111111111111111111111", "Bchass", "Nmplade", "Year", "color1111111111111" }; string binFile = "\u001bia\u0003^II^TS001^ONModel\0^DI\u0010\0Modelnavn1111111^ONVariant\0^DI\u001c\0Variant111111111111111111111^ONbchass\0^DI\u0006\0Bchass^ONnmplade\0^DI\u0007\0Nmplade^ONyear\0^DI\u0004\0Year^ONColor\0^DI\u0012\0color1111111111111^FF"; for (int i = 0; i <replaceWith.Length - 1; i++) { hexstrings[i] = #"\u" + lines[i].Length.ToString("X4"); Console.WriteLine(hexstrings[i]); } for (int i = 0; i < replaceWith.Length; i++) { while (replaceWith[i].Length > lines[i].Length) { lines[i] += " "; } binFile = binFile.Replace(replaceWith[i], lines[i]); } //File.WriteAllText("C:\\HireLabel\\print.bin", binFile); //Process.Start("cmd.exe", "/C C:\\HireLabel\\spool.exe C:\\HireLabel\\print.bin " + "\"" + lines[replaceWith.Length] + "\""); } The program write now, writes for an example "0007" in the console, and it should give some wierd chinese looking letters, instead of the numbers. but the number is the number in hex, so that part is converted right.
How to efficiently edit data within a C# String Array
I'm working on a simple program to edit data within a string array, and have been scratching my head over this for the past few nights. I'm relatively new to C# and would really appreciate some help. I want to edit a string array into something that looks like this (in theory): [Section] Key: Data Key2: Data Key3: Data If the section isn't found, it should be created (along with another line containing the key & data passed to the method). If it is found, it should be checked until the next section (or the end of the file). If the key is not found within the section, it should be created at the end of the section. If it is found, the data of the key should be edited. What's the best way of doing this? I've tried a few times with some super hacky code and always wind up with something like this: [Section] Key3: System.String[] Sorry if this isn't the best question. I'm relatively new to C#, as I've said, and could really use the help. Thanks.
"edit data within a string array" string[] myArray = { "one", "two", "three" }; myArray[1] = "nottwo"; Second value (myArray[1]) has changed from two to nottwo. Now going deeper into the description of your problem... You have mentioned keys & values, for this you will very likely want to look into Dictionary<TKey,TValue> Class. See reference: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.8 Example: Dictionary<int, string> myDictionary = new Dictionary<string, string>(); myDictionary.Add("one", "Hello"); myDictionary.Add("two", "World"); myDictionary.Add("three", "This is"); myDictionary.Add("sandwich", "a Dictionary."); Console.Writeline(myDictionary["one"]); Console.Writeline(myDictionary["two"]); Console.Writeline(myDictionary["three"]); Console.Writeline(myDictionary["sandwich"]);
I've found some code that works for my use case. public static string[] SetData(string section, string key, string value, string[] data) { var updatedData = data; int sectionIndex = Array.IndexOf(data, "[" + section + "]"); if(sectionIndex > -1) { //section found for(int i = sectionIndex; i < data.Length; i++) { if (data[i].StartsWith(key)) { //key found string newData = data[i]; string tempString = newData.Remove(newData.LastIndexOf(":")); updatedData[i] = tempString + ": " + value; break; } else if (data[i].StartsWith("[") && !data[i].Contains(section)) { //key not found, end of section reached. List<string> temp = data.ToList(); temp.Insert(i, key + ": " + value); updatedData = temp.ToArray(); break; } else if (i == data.Length - 1) //-1? { //key not found, end of file reached. List<string> temp = data.ToList(); temp.Insert(i, key + ": " + value); updatedData = temp.ToArray(); break; } } return updatedData; } else { //section not found updatedData = new string[data.Length + 2]; for (int i = 0; i < data.Length; i++) { updatedData[i] = data[i]; } updatedData[updatedData.Length - 2] = "[" + section + "]"; updatedData[updatedData.Length - 1] = key + ": " + value; return updatedData; } }
convert number index of string array to double array
I am reading from a text file, pulling each line, looking for the first line with 1|, and then converting it into an array. For this I only want the 4th index so that I can sum and count the array. Here is what is converts from the text file into an array 1|123456|01/06/2019|123456|100.00|USD|DUE UPON RECEIPT|TEST1||98790125|TEST2|TEST3|N so [0] = 1, [2] = 123456, etc. etc. I am trying to pull 100.00 from it and put it in it's own array, so that I can easily double sum, and count the elements. It's proving difficult for me since the original array is a string though. I've tried creating a separate string array already split, and then pulling the 4th index and creating an double array that I can count and sum. I've also tried just splitting and creating an int array in one line from the str it pulls. string str; using (StreamReader file = new StreamReader("c:\\testdoc.txt")) while ((str = file.ReadLine()) != null) { string[] strArray = str.Split('|'); if (strArray[0] == "1") { double[] itotals = strArray.Select(i => Convert.ToDouble(i)).ToArray(); int count = itotals.Length; double amt = itotals.Sum(); Console.WriteLine("Count: " + count + " Amt: " + amt); } else { } } I expect it to find the line starting with 1|, then tell console to write count: 1 amt: 100.00, but I actually just get errors that input strings were not in the correct format. I know that I need to pull the 4th index after I split, but I'm not sure where to do that.
Try this string str; int count = 0; double amt = 0; using (StreamReader file = new StreamReader("c:\\testdoc.txt")) while ((str = file.ReadLine()) != null) { string[] strArray = str.Split('|'); if (strArray[0] == "1") { string itotals = strArray[4]; count = count+1; amt = amt + Convert.ToDouble(strArray[4]); Console.WriteLine("Count: " + count + " Amt: " + amt); } else { } }
populating multiple comboBoxes from elements in a string list
I have a list of input curve names in a text file called inCurves.txt. The .txt file reads: 18500*8500*Eval:c3*Eval:c2*Eval:c1*Final:DTS*Final:OBG*Final:PPG* The first two numbers are bottom and top depth, while the remainder are curveSet names and curve names for every remaining comboBox (1 - 6) I've written a script to populate comboBoxes from this .txt, but I receive an error when I try to convert cmbBox into string, and then into an integer. input string was not in a correct format) private void btnLoad_Click(object sender, EventArgs e) { try { string CurveNamesInText = ""; char[] delimiter = { '*' }; CurveNamesInText = System.IO.File.ReadAllText(#"C:\Users\Public\inCurves.txt"); string[] crvIn = CurveNamesInText.Split(delimiter); string BottomDepth = crvIn[0]; string TopDepth = crvIn[1]; var combBoxes = this.Controls.OfType<ComboBox>().Where(x => x.Name.StartsWith("comboBox")); foreach (var cmbBox in combBoxes) { string yes = Convert.ToString(cmbBox); string number = yes.Replace("comboBox","0"); int i = Convert.ToInt16(number); //error here, comp doesn't like it MessageBox.Show("current number value \n" + number + "\n" + "current i value \n" + i); //cmbBox.Text = crvIn[6-i]; // this is what I'd like to do next } } catch (Exception ex) { MessageBox.Show("Error Loading Curve names \n" + ex.Message + "\n" + ex.StackTrace); } } I would like to assign an element in crvIn list to each comboBox. Ideally, something like this: cmbBox.Text = crvIn[i]; Can you help?
The problem is that you are trying to convert an entire object ComboBox into a string, which will result only in the full name of the class/type ComboBox plus the item count: "System.Windows.Controls.ComboBox Items.Count:0" You can also see this in the Debugger. I would like to assign an element in crvIn list to each comboBox I guess if you want to add each value to a different combobox you could use a for-loop and add the items. You need to add it to the items, if you want to make them selectable. First you need to make a list from your query. Add ToList() at the end: var combBoxes = this.Controls.OfType<ComboBox>() .Where(x => x.Name.StartsWith("comboBox")).ToList(); for (int i = 0; i < combBoxes.Count; i++) { combBoxes[i].Text = crvIn[i + 2]; }
How to parse below string in C#?
Please someone to help me to parse these sample string below? I'm having difficulty to split the data and also the data need to add carriage return at the end of every event sample string: L,030216,182748,00,FF,I,00,030216,182749,00,FF,I,00,030216,182750,00,FF,I,00 batch of events expected output: L,030216,182748,00,FF,I,00 - 1st Event L,030216,182749,00,FF,I,00 - 2nd Event L,030216,182750,00,FF,I,00 - 3rd Event
Seems like an easy problem. Something as easy as this should do it: string line = "L,030216,182748,00,FF,I,00,030216,182749,00,FF,I,00,030216,182750,00,FF,I,00"; string[] array = line.Split(','); StringBuilder sb = new StringBuilder(); for(int i=0; i<array.Length-1;i+=6) { sb.AppendLine(string.Format("{0},{1} - {2} event",array[0],string.Join(",",array.Skip(i+1).Take(6)), "number")); } output (sb.ToString()): L,030216,182748,00,FF,I,00 - number event L,030216,182749,00,FF,I,00 - number event L,030216,182750,00,FF,I,00 - number event All you have to do is work on the function that increments the ordinals (1st, 2nd, etc), but that's easy to get.
This should do the trick, given there are no more L's inside your string, and the comma place is always the sixth starting from the beginning of the batch number. class Program { static void Main(string[] args) { String batchOfevents = "L,030216,182748,00,FF,I,00,030216,182749,00,FF,I,00,030216,182750,00,FF,I,00,030216,182751,00,FF,I,00,030216,182752,00,FF,I,00,030216,182753,00,FF,I,00"; // take out the "L," to start processing by finding the index of the correct comma to slice. batchOfevents = batchOfevents.Substring(2); String output = ""; int index = 0; int counter = 0; while (GetNthIndex(batchOfevents, ',', 6) != -1) { counter++; if (counter == 1){ index = GetNthIndex(batchOfevents, ',', 6); output += "L, " + batchOfevents.Substring(0, index) + " - 1st event\n"; batchOfevents = batchOfevents.Substring(index + 1); } else if (counter == 2) { index = GetNthIndex(batchOfevents, ',', 6); output += "L, " + batchOfevents.Substring(0, index) + " - 2nd event\n"; batchOfevents = batchOfevents.Substring(index + 1); } else if (counter == 3) { index = GetNthIndex(batchOfevents, ',', 6); output += "L, " + batchOfevents.Substring(0, index) + " - 3rd event\n"; batchOfevents = batchOfevents.Substring(index + 1); } else { index = GetNthIndex(batchOfevents, ',', 6); output += "L, " + batchOfevents.Substring(0, index) + " - " + counter + "th event\n"; batchOfevents = batchOfevents.Substring(index + 1); } } output += "L, " + batchOfevents + " - " + (counter+1) + "th event\n"; Console.WriteLine(output); } public static int GetNthIndex(string s, char t, int n) { int count = 0; for (int i = 0; i < s.Length; i++) { if (s[i] == t) { count++; if (count == n) { return i; } } } return -1; } } Now the output will be in the format you asked for, and the original string has been decomposed. NOTE: the getNthIndex method was taken from this old post.
If you want to split the string into multiple strings, you need a set of rules, which are implementable. In your case i would start splitting the complete string by the given comma , and than go though the elements in a loop. All the strings in the loop will be appended in a StringBuilder. If your ruleset say you need a new line, just add it via yourBuilder.Append('\r\n') or use AppendLine. EDIT Using this method, you can also easily add new chars like L or at the end rd Event
Look for the start index of 00,FF,I,00 in the entire string. Extract a sub string starting at 0 and index plus 10 which is the length of the characters in 1. Loop through it again each time with a new start index where you left of in 2. Add a new line character each time.
Have a try the following: string stream = "L,030216,182748,00,FF,I,00, 030216,182749,00,FF,I,00, 030216,182750,00,FF,I,00"; string[] lines = SplitLines(stream, "L", "I", ","); Here the SplitLines function is implemented to detect variable-length events within the arbitrary-formatted stream: string stream = "A;030216;182748 ;00;FF;AA;01; 030216;182749;AA;02"; string[] lines = SplitLines(batch, "A", "AA", ";"); Split-rules are: - all elements of input stream are separated by separator(, for example). - each event is bounded by the special markers(L and I for example) - end marker is previous element of event-sequence static string[] SplitLines(string stream, string startSeq, string endLine, string separator) { string[] elements = stream.Split(new string[] { separator }, StringSplitOptions.RemoveEmptyEntries); int pos = 0; List<string> line = new List<string>(); List<string> lines = new List<string>(); State state = State.SeqStart; while(pos < elements.Length) { string current = elements[pos].Trim(); switch(state) { case State.SeqStart: if(current == startSeq) state = State.LineStart; continue; case State.LineStart: if(++pos < elements.Length) { line.Add(startSeq); state = State.Line; } continue; case State.Line: if(current == endLine) state = State.LineEnd; else line.Add(current); pos++; continue; case State.LineEnd: line.Add(endLine); line.Add(current); lines.Add(string.Join(separator, line)); line.Clear(); state = State.LineStart; continue; } } return lines.ToArray(); } enum State { SeqStart, LineStart, Line, LineEnd };
f you want to split the string into multiple strings, you need a set of rules, which are implementable. In your case i would start splitting the complete string by the given comma , and than go though the elements in a loop. All the strings in the loop will be appended in a StringBuilder. If your ruleset say you need a new line, just add it via yourBuilder.Append('\r\n') or use AppendLine.