C# - Building an Array from Text File - c#

I am attempting to build an array of batting averages from a .txt file, but most of the resources I am finding online to assist in how to work this out either work with text in the following format:
1 2 3 4 5
2 3 4 5 6
etc.
... or in the following format:
1, 2
3, 4
etc.
Unfortunately, my text file is in the following format, and changing the format is not an option. Each odd line number denotes a player, with the following even line number being their average at bat in that instance (just information for context):
1
2
3
4
Using this file, I want to assign the odd numbers to the index of the array, and then populate the even numbers as values, calculating them as I go. I believe that I can parse out how to accomplish the calculations, I just cannot ascertain how to grab the data nor associate the odd numbers with array indexes.
Code as follows. File is to be specified by user:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
static string FileName()
{
string doc = Console.ReadLine();
return doc;
}
static void Main(string[] args)
{
try
{
Console.Write("Where is the data file for batting averages located? ");
string doc = FileName();
StreamReader reader = new StreamReader(doc);
string avg = reader.ReadToEnd();
reader.Close();
}
catch (System.IO.FileNotFoundException)
{
Console.WriteLine("The file can not be found.");
}
catch (System.FormatException)
{
Console.WriteLine("Invalid file.");
}
catch (System.ArgumentException)
{
Console.WriteLine("Enter a valid file name.");
}
catch (System.Exception exc)
{
Console.WriteLine(exc.Message);
}
}
Any assistance would be welcome. Please keep in mind I am a student and still learning the earliest parts of C#, so any truly advanced techniques are probably going to be lost on me.

You can read the Text file Line by line (or use System.IO.File.ReadAllLines - to get a string[] - Link). Now Odd/Even indices can be read and processed per your wish.
Tip: Your text file format is basic and error prone.

You can do something like this:
var lines = File.ReadAllLines(FileName());
for (int i = 0; i < lines.Length; i += 2)
{
Console.WriteLine($"Player Name: {lines[i]}");
Console.WriteLine($"Player Average: {lines[i + 1]}");
}

After working late into the night yesterday, I came up with code that resolved my issue:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
class Program
{
static void Main(string[] args)
{
Console.Write("Where is the data file for batting averages located? ");
string doc = Console.ReadLine();
int[] avg = new int[9];
int val1=0, val2=0, val3=0, val4=0, val5=0, val6=0, val7=0, val8=0, val9=0;
int cnt1=0, cnt2=0, cnt3=0, cnt4=0, cnt5=0, cnt6=0, cnt7=0, cnt8=0, cnt9=0;
try
{
StreamReader reader = new StreamReader(doc);
var lines = File.ReadAllLines(doc);
int[] index = Array.ConvertAll(lines, int.Parse);
//Console.WriteLine(lines); //displays contents of text file
reader.Close();
for (int i = 0; i < index.Length; i += 2)
{
switch (index[i])
{
case 1:
cnt1++;
val1 = val1 + index[i + 1];
break;
case 2:
cnt2++;
val2 = val2 + index[i + 1];
break;
case 3:
cnt3++;
val3 = val3 + index[i + 1];
break;
case 4:
cnt4++;
val4 = val4 + index[i + 1];
break;
case 5:
cnt5++;
val5 = val5 + index[i + 1];
break;
case 6:
cnt6++;
val6 = val6 + index[i + 1];
break;
case 7:
cnt7++;
val7 = val7 + index[i + 1];
break;
case 8:
cnt8++;
val8 = val8 + index[i + 1];
break;
case 9:
cnt9++;
val9 = val9 + index[i + 1];
break;
default:
break;
}
}
int total = cnt1 + cnt2 + cnt3 + cnt4 + cnt5 + cnt6 + cnt7 + cnt8 + cnt9;
decimal avg1 = Convert.ToDecimal(val1) / Convert.ToDecimal(cnt1);
decimal avg2 = Convert.ToDecimal(val2) / Convert.ToDecimal(cnt2);
decimal avg3 = Convert.ToDecimal(val3) / Convert.ToDecimal(cnt3);
decimal avg4 = Convert.ToDecimal(val4) / Convert.ToDecimal(cnt4);
decimal avg5 = Convert.ToDecimal(val5) / Convert.ToDecimal(cnt5);
decimal avg6 = Convert.ToDecimal(val6) / Convert.ToDecimal(cnt6);
decimal avg7 = Convert.ToDecimal(val7) / Convert.ToDecimal(cnt7);
decimal avg8 = Convert.ToDecimal(val8) / Convert.ToDecimal(cnt8);
decimal avg9 = Convert.ToDecimal(val9) / Convert.ToDecimal(cnt9);
Console.WriteLine("{0} pairs of data read.", total);
Console.WriteLine("The batting average for:");
Console.WriteLine(" position 1 is {0}", Math.Round(avg1, 4));
Console.WriteLine(" position 2 is {0}", Math.Round(avg2, 4));
Console.WriteLine(" position 3 is {0}", Math.Round(avg3, 4));
Console.WriteLine(" position 4 is {0}", Math.Round(avg4, 4));
Console.WriteLine(" position 5 is {0}", Math.Round(avg5, 4));
Console.WriteLine(" position 6 is {0}", Math.Round(avg6, 4));
Console.WriteLine(" position 7 is {0}", Math.Round(avg7, 4));
Console.WriteLine(" position 8 is {0}", Math.Round(avg8, 4));
Console.WriteLine(" position 9 is {0}", Math.Round(avg9, 4));
}
catch (System.IO.FileNotFoundException) //file not present
{
Console.WriteLine("The file {0} was not found.", doc);
}
catch (System.IndexOutOfRangeException)
{
Console.WriteLine("Incomplete data pairs. Please re-check your data entries and retry.");
}
catch (System.FormatException) //bad data
{
Console.WriteLine("Invalid file.");
}
catch (System.ArgumentException) //null entry
{
Console.WriteLine("Make sure you enter a valid file name.");
}
catch (System.Exception exc) //any other exceptions
{
Console.WriteLine(exc.Message);
}
}
}
}
I know parts of it are a bit clunky, but as long as it works, I can learn more about condensing the information as I attend more classes. Thank you both for your assistance.

Related

Receipt like output in c#

int choice, quanti, decide, total, cash;
double change;
string dcount;
while (true)
{
Console.Clear();
string w = "WELCOME ";
Console.SetCursorPosition((Console.WindowWidth - w.Length) / 2, Console.CursorTop); // for setting string output on center top
Console.WriteLine(w);
Console.WriteLine("");
System.Threading.Thread.Sleep(2000); //time delay
string p = "HERE'S OUR MERCHANDISES! ";
Console.SetCursorPosition((Console.WindowWidth - p.Length) / 2, Console.CursorTop); // for setting string output on center top
Console.WriteLine(p);
System.Threading.Thread.Sleep(2000);//time delay
string[] products = { "[1]BLACKPINK Lightstick ", "[2]DREAMCATCHER Seasons Greetings",
"[3]RED VELVET Summer Package"};
for (int g = 0; g < products.Length; g++)
{
Console.WriteLine(products[g]);
}
Dictionary<int, int> ProductList = new Dictionary<int, int>();
while (true)
{
{
Console.Write("Pick your product: ");
choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
Console.WriteLine("BLACKPINK Lightstick 1500php");
break;
case 2:
Console.WriteLine("DREAMCATCHER Seasons Greetings 920php");
break;
case 3:
Console.WriteLine("RED VELVET Summer Package 980php");
break;
}
Console.WriteLine("Quantity of product: ");
quanti = int.Parse(Console.ReadLine());
if (!ProductList.ContainsKey(choice))
ProductList.Add(choice, quanti);
else
ProductList[choice] += quanti;
System.Threading.Thread.Sleep(2000);//time delay
Console.WriteLine("[1] Add more products \t [2] Pay: ");
decide = int.Parse(Console.ReadLine());
if (decide == 2)
break;
}
}
total = 0;
foreach (int key in ProductList.Keys)
switch (key)
{
case 1:
total += ProductList[key] * 1500;
break;
case 2:
total += ProductList[key] * 920;
break;
case 3:
total += ProductList[key] * 980;
break;
default:
total += 0;
break;
};
Console.WriteLine("To Pay: " + total);
Console.Write("Cash: ");
cash = Convert.ToInt32(Console.ReadLine());
Console.Write("Discount[s]suki [v]voucher: ");
dcount = Console.ReadLine();
if (dcount == "s")
{
change = (cash - total) - 0.7;
Console.WriteLine("Change: " + change);
}
else if (dcount == "v")
{
change = cash -(total - 0.5) ;
Console.WriteLine("Change: " + change);
}
else
{
change = cash- (total - 0.7) ;
Console.WriteLine("Change: " + change);
}
Console.WriteLine("Another shopping? [1]Yes [2] No");
choice = int.Parse(Console.ReadLine());
if (choice == 2)
break;
}
}
}
}
Good day, I'm doing a project for school. I've already asked earlier about my code and someone help me, thanks to him, unfortunately I still have a problem with my code. After the users inputs and giving her a change, it was supposed to output a receipt like, wherein it contains users purchased products. I've tried outputting the variables that have been used in acquiring users input but to my dismay, it can only output the user's first input product, it can't Output all the users purchase. The receipt like output was supposed to contain the user's products purchased, quantity of each product, total, cash, discount and change in horizontal line/tabular.
Quick way of printing out products and quantity for each would be to put after dcount = Console.ReadLine(); something like:
foreach(var entry in ProductList)
{
Console.WriteLine(products[entry.Key].Substring(3) + "......." + entry.Value);
}
I'll leave the amount of dots and cursor position to You.
Also, when dealing with currency it's better to use decimal due to higher precision (maybe not needed in this example.) And try to use Math.Round() function when displaying money amount - limit decimal places.

Creating a running total for a coin counter

I'm working on making a running total for a coin calculator we're creating for a school project. It's a C# program running in Visual Studio 2019. Currently, I have it adding total change for a single instance, but I need to add a running total that shows before you end the program.
I've tried looking online, but I cant seem to find code that would fit into what I am making. I'm a beginner with C#, so all my ideas have fallen short. Here is my code; hopefully someone can help me out. (Note that the running total should go into the while statement when the user enters N.)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
namespace CalcChange
{
class Program
{
static void Main(string[] args)
{
string choice;
int q, d, n, p, hd;
int totchange, totcents, dollars, cents;
Console.WriteLine("Welcome to the Change Calculator");
Console.Write("Do you have change? (y/n): ");
choice = Console.ReadLine();
while (choice.Equals("Y", StringComparison.CurrentCultureIgnoreCase))
{
hd = getCoin("Helf Dollars");
q = getCoin("Quarters");
d = getCoin("Dimes");
n = getCoin("Nickels");
p = getCoin("Pennies");
totcents = (hd * 50) + (q * 25) + (d * 10) + (n * 5) + p;
Console.WriteLine("\nYou have " + totcents + " Cents.");
dollars = totcents / 100;
cents = totcents % 100;
Console.WriteLine("Which is " + dollars + " dollars and "
+ cents + " cents.\n");
Console.WriteLine("I'm in the loop!");
Console.Write("Do you have more change? (y/n): ");
choice = Console.ReadLine();
}
while (choice.Equals("N", StringComparison.CurrentCultureIgnoreCase))
{
}
if (Debugger.IsAttached)
{
Console.Write("Press any key to Continue...");
Console.ReadKey();
}
} //end of main
static int getCoin(string cointype)
{
int ccount;
do
{
try
{
Console.Write("How many " + cointype + " do you have?");
ccount = int.Parse(Console.ReadLine());
if (ccount < 0)
{
Console.WriteLine("Coin amounts cannot be negative, please re-enter a valid amount.");
}
}
catch (Exception ex)
{
Console.WriteLine("Illegal input: " + ex.Message + " please re-enter a valid amount.");
ccount = -1;
}
} while (ccount < 0);
return ccount;
}
} //end of class
}
Well just keep a variable that will sum all iterations
For example:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
namespace CalcChange
{
class Program
{
static void Main(string[] args)
{
string choice;
int q, d, n, p, hd;
int totchange, totcents, dollars, cents;
int grandTotal = 0;
Console.WriteLine("Welcome to the Change Calculator");
Console.Write("Do you have change? (y/n): ");
choice = Console.ReadLine();
while (choice.Equals("Y", StringComparison.CurrentCultureIgnoreCase))
{
hd = getCoin("Helf Dollars");
q = getCoin("Quarters");
d = getCoin("Dimes");
n = getCoin("Nickels");
p = getCoin("Pennies");
totcents = (hd * 50) + (q * 25) + (d * 10) + (n * 5) + p;
Console.WriteLine("\nYou have " + totcents + " Cents.");
// once the user puts his change add the total cents to the grandtotal
// variable
grandTotal += totcents;
dollars = totcents / 100;
cents = totcents % 100;
Console.WriteLine("Which is " + dollars + " dollars and "
+ cents + " cents.\n");
Console.WriteLine("I'm in the loop!");
Console.Write("Do you have more change? (y/n): ");
choice = Console.ReadLine();
}
while (choice.Equals("N", StringComparison.CurrentCultureIgnoreCase))
{
}
// here print the value
Console.WriteLine($"You have a total of {grandTotal / 100} dollars and {grandTotal % 100} cents");
if (Debugger.IsAttached)
{
Console.Write("Press any key to Continue...");
Console.ReadKey();
}
} //end of main
static int getCoin(string cointype)
{
int ccount;
do
{
try
{
Console.Write("How many " + cointype + " do you have?");
ccount = int.Parse(Console.ReadLine());
if (ccount < 0)
{
Console.WriteLine("Coin amounts cannot be negative, please re-enter a valid amount.");
}
}
catch (Exception ex)
{
Console.WriteLine("Illegal input: " + ex.Message + " please re-enter a valid amount.");
ccount = -1;
}
} while (ccount < 0);
return ccount;
}
} //end of class
}
I added some comments in the code for more clarity
Hope this helps

C# How can I handle this exception?

I am new to C# and trying to create a GPA calculator using a sentinel controlled loop. To end the loop, I want the user to enter an 'x', but it is throwing an exception. I'm pretty sure it is because 'x' is not a double type, but I am not sure how I can make it work. I was using a number to exit before but it kept being added to the gradeTotal. Any suggestions would be great! Thanks!
Code:
class Program
{
static void Main(string[] args)
{
double gradeTotal = 0;
int[] score = new int[100];
string inValue;
int scoreCnt = 0;
Console.WriteLine("When entering grades, use a 0-4 scale. Remember;
A = 4, B = 3, C = 2, D = 1, F = 0");
Console.WriteLine("Enter grade {0}: ((X to exit)) ", scoreCnt + 1);
inValue = Console.ReadLine();
gradeTotal += double.Parse(inValue);//This may be a problem area
while (inValue != "x")
{
if (int.TryParse(inValue, out score[scoreCnt]) == false)
Console.WriteLine("Invalid data -" + "0 stored in array");
++scoreCnt;
Console.WriteLine("Enter Score{0}: ((X to exit)) ", scoreCnt +
1);
inValue = Console.ReadLine();
gradeTotal += double.Parse(inValue);//This is a problem area
}
Console.WriteLine("The number of scores: " + scoreCnt);
Console.WriteLine("Your GPA is: " + gradeTotal);//Obviously not the
//right calculation, just trying to figure it out
Console.ReadLine();
}
}
Least effort
Instead of
gradeTotal += double.Parse(inValue);//This is a problem area
Try
if (inValue == "X") break;
gradeTotal += double.Parse(inValue);
More robust
double d;
var ok = double.TryParse(inValue, out d);
if (!ok) break;
gradeTotal += d;
You have zero validation on the inValue before trying to parse it. That's the problem. How you resolve this is up to you. Here's a couple suggestions:
wrap the code in a try...catch...
try {
grandTotal += double.Parse(inValue);
} catch (Exception e) {
Console.WriteLine("Invalid input!");
}
Use Regular Expressions to validate user input and return error if not a number
(System.Text.RegularExpressions.Regex)

Writing items from listbox to text file in C# with try-catch statment

My code it quite long but this is the part that I am stuck on. I have my try statement at the beginning before my for loops. But now I want to take my information that is in the ListBox and send it to a text file which I already have in my debug folder. I would like to just take my outputs from the list box and write them to the population.txt file.
//variable user input, store in userInput
try
{
if (double.TryParse(startTextbox.Text, out start))
{
if (double.TryParse(averageTextbox.Text, out average))
{
if (double.TryParse(daysTextbox.Text, out days))
{
//process
int count = 1;
while (count <= days)
{
//calculation
double output;
output = start * Math.Pow((1 + average / 100), count - 1);
//display the results in the listbox
populationListBox.Items.Add("The approximate population for " +
count + " day(s) is " + output.ToString("n2"));
//count the days
count = count + 1;
}
//used to text statement
//populationListBox.Items.Add("End of while loop");
count = 1;
do
{
//calculation
double output;
output = start * Math.Pow((1 + average / 100), count - 1);
//display the results in the listbox
populationListBox.Items.Add("The approximate population for " +
count + " day(s) is " + output.ToString("n2"));
//count the days
count = count + 1;
} while (count <= days);
//used to text statement
//populationListBox.Items.Add("End of do-while loop");
//int count;
for (count = 1; count <= days; )
{
//calculation
double output;
output = start * Math.Pow((1 + average / 100), count - 1);
//display the results in the listbox
populationListBox.Items.Add("The approximate population for " +
count + " day(s) is " + output.ToString("n2"));
//count the days
count = count + 1;
}
//used to text statement
//populationListBox.Items.Add("End of for loop");
}
else
{
//error message for input
MessageBox.Show("Invalid input for number of days to multiply.");
}
}
else
{
//error message for input
MessageBox.Show("Invalid input for average daily increase.");
}
}
else
{
//error message for input
MessageBox.Show("Invalid input for starting days");
}
StreamWriter outputFile;
outputFile = File.CreateText("population.txt");
outputFile.WriteLine("Approximate population: ");
outputFile.WriteLine(populationListBox.Items);
outputFile.ToString();
outputFile.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You can use library like FileHelper to perform your job. It is open source and free. If you want to use just FileIO from .NET framework you can do that also
using (StreamWriter sr = File.CreateText("population.txt"))
{
foreach (string s in listBox.Items)
{
sr.WriteLine(s);
}
}

Faster than String.Replace()

Is there any other method that is faster than doing like this?
private void EscapeStringSequence(ref string data)
{
data = data.Replace("\\", "\\\\"); // Backslash
data = data.Replace("\r", "\\r"); // Carriage return
data = data.Replace("\n", "\\n"); // New Line
data = data.Replace("\a", "\\a"); // Vertical tab
data = data.Replace("\b", "\\b"); // Backspace
data = data.Replace("\f", "\\f"); // Formfeed
data = data.Replace("\t", "\\t"); // Horizontal tab
data = data.Replace("\v", "\\v"); // Vertical tab
data = data.Replace("\"", "\\\""); // Double quotation mark
data = data.Replace("'", "\\'"); // Single quotation mark
}
-- Edited (Add explanation) --
Q1: Is there a reason why you need to speed it up? Is it causing a huge problem?
This part is used in this project: http://mysqlbackuprestore.codeplex.com/
I'm going to loop lots of various length of strings into this function repeatly. The whole process takes around 6-15 seconds to finished for millions of rows. There are other part get involve too. I'm trying to speed up every part.
Q2: How slow is it now?
OK, I'll capture the exact time used and post it here. I'll come back later. (will post the result tomorrow)
Update 29-06-2012
I have run test. This is the result:
Speed Test: String.Replace() - measured in miliseconds
Test 1: 26749.7531 ms
Test 2: 27063.438 ms
Test 3: 27753.8884 ms
Average: 27189.0265 ms
Speed: 100%
Speed Test: Foreach Char and Append - measured in miliseconds
Test 1: 8468.4547 ms
Test 2: 8348.8527 ms
Test 3: 8353.6476 ms
Average: 8390.3183 ms
Speed: 224% < faster
===================================
Update - Next Test (Another round)
===================================
------
Test Replace String Speed.
Test 1: 26535.6466
Test 2: 26379.6464
Test 3: 26379.6463
Average: 26431.6464333333
Speed: 100%
------
Test Foreach Char String Append.
Test 1: 8502.015
Test 2: 8517.6149
Test 3: 8595.6151
Average: 8538.415
Speed: 309.56%
------
Test Foreach Char String Append (Fix StringBuilder Length).
Test 1: 8314.8146
Test 2: 8330.4147
Test 3: 8346.0146
Average: 8330.41463333333
Speed: 317.29%
Conclusion:
Using Foreach Char Loop and Append is faster than String.Replace().
Thanks you very much guys.
--------
Below are the codes that I used to run the test: (edited)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Press any key to continue...");
Console.ReadKey();
Console.Write("\r\nProcess started.");
Test();
Console.WriteLine("Done.");
Console.Read();
}
public static Random random = new Random((int)DateTime.Now.Ticks);
public static string RandomString(int size)
{
StringBuilder sb = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
sb.Append(ch);
}
return sb.ToString();
}
public static void Test()
{
string text = "\\_\r\n\a\b\f\t\v\"'" + RandomString(2000) + "\\_\r\n\a\b\f\t\v\"'" + RandomString(2000);
List<TimeSpan> lstTimeUsed = new List<TimeSpan>();
int target = 100000;
for (int i = 0; i < 3; i++)
{
DateTime startTime = DateTime.Now;
for (int j = 0; j < target; j++)
{
if (j.ToString().EndsWith("000"))
{
Console.Clear();
Console.WriteLine("Test " + i.ToString());
Console.WriteLine(j.ToString() + " of " + target.ToString());
}
string data = text;
data = data.Replace("\\", "\\\\"); // Backslash
data = data.Replace("\r", "\\r"); // Carriage return
data = data.Replace("\n", "\\n"); // New Line
data = data.Replace("\a", "\\a"); // Vertical tab
data = data.Replace("\b", "\\b"); // Backspace
data = data.Replace("\f", "\\f"); // Formfeed
data = data.Replace("\t", "\\t"); // Horizontal tab
data = data.Replace("\v", "\\v"); // Vertical tab
data = data.Replace("\"", "\\\""); // Double quotation mark
data = data.Replace("'", "\\'"); // Single quotation mark
}
DateTime endTime = DateTime.Now;
TimeSpan ts = endTime - startTime;
lstTimeUsed.Add(ts);
}
double t1 = lstTimeUsed[0].TotalMilliseconds;
double t2 = lstTimeUsed[1].TotalMilliseconds;
double t3 = lstTimeUsed[2].TotalMilliseconds;
double tOri = (t1 + t2 + t3) / 3;
System.IO.TextWriter tw = new System.IO.StreamWriter("D:\\test.txt", true);
tw.WriteLine("------");
tw.WriteLine("Test Replace String Speed. Test Time: " + DateTime.Now.ToString());
tw.WriteLine("Test 1: " + t1.ToString());
tw.WriteLine("Test 2: " + t2.ToString());
tw.WriteLine("Test 3: " + t3.ToString());
tw.WriteLine("Average: " + tOri.ToString());
tw.WriteLine("Speed: 100%");
tw.Close();
lstTimeUsed = new List<TimeSpan>();
for (int i = 0; i < 3; i++)
{
DateTime startTime = DateTime.Now;
for (int j = 0; j < target; j++)
{
if (j.ToString().EndsWith("000"))
{
Console.Clear();
Console.WriteLine("Test " + i.ToString());
Console.WriteLine(j.ToString() + " of " + target.ToString());
}
string data = text;
var builder = new StringBuilder();
foreach (var ch in data)
{
switch (ch)
{
case '\\':
case '\r':
case '\n':
case '\a':
case '\b':
case '\f':
case '\t':
case '\v':
case '\"':
case '\'':
builder.Append('\\');
break;
default:
break;
}
builder.Append(ch);
}
}
DateTime endTime = DateTime.Now;
TimeSpan ts = endTime - startTime;
lstTimeUsed.Add(ts);
}
t1 = lstTimeUsed[0].TotalMilliseconds;
t2 = lstTimeUsed[1].TotalMilliseconds;
t3 = lstTimeUsed[2].TotalMilliseconds;
tw = new System.IO.StreamWriter("D:\\test.txt", true);
tw.WriteLine("------");
tw.WriteLine("Test Foreach Char String Append. Test Time: " + DateTime.Now.ToString());
tw.WriteLine("Test 1: " + t1.ToString());
tw.WriteLine("Test 2: " + t2.ToString());
tw.WriteLine("Test 3: " + t3.ToString());
tw.WriteLine("Average: " + ((t1 + t2 + t3) / 3).ToString());
tw.WriteLine("Speed: " + ((tOri) / ((t1 + t2 + t3) / 3) * 100).ToString("0.00") + "%");
tw.Close();
lstTimeUsed = new List<TimeSpan>();
for (int i = 0; i < 3; i++)
{
DateTime startTime = DateTime.Now;
for (int j = 0; j < target; j++)
{
if (j.ToString().EndsWith("000"))
{
Console.Clear();
Console.WriteLine("Test " + i.ToString());
Console.WriteLine(j.ToString() + " of " + target.ToString());
}
string data = text;
var builder = new StringBuilder(data.Length + 20);
foreach (var ch in data)
{
switch (ch)
{
case '\\':
case '\r':
case '\n':
case '\a':
case '\b':
case '\f':
case '\t':
case '\v':
case '\"':
case '\'':
builder.Append('\\');
break;
default:
break;
}
builder.Append(ch);
}
}
DateTime endTime = DateTime.Now;
TimeSpan ts = endTime - startTime;
lstTimeUsed.Add(ts);
}
t1 = lstTimeUsed[0].TotalMilliseconds;
t2 = lstTimeUsed[1].TotalMilliseconds;
t3 = lstTimeUsed[2].TotalMilliseconds;
tw = new System.IO.StreamWriter("D:\\test.txt", true);
tw.WriteLine("------");
tw.WriteLine("Test Foreach Char String Append (Fix StringBuilder Length). Test Time: " + DateTime.Now.ToString());
tw.WriteLine("Test 1: " + t1.ToString());
tw.WriteLine("Test 2: " + t2.ToString());
tw.WriteLine("Test 3: " + t3.ToString());
tw.WriteLine("Average: " + ((t1 + t2 + t3) / 3).ToString());
tw.WriteLine("Speed: " + ((tOri) / ((t1 + t2 + t3) / 3) * 100).ToString("0.00") + "%");
tw.Close();
}
}
}
var builder = new StringBuilder(data.Length + 20);
foreach (var ch in data)
{
switch (ch)
{
case '\\':
case '\r':
...
builder.Append('\\');
break;
}
builder.Append(ch);
}
return builder.ToString();
Try using a series of StringBuilder calls.

Categories