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.
Related
I read strings from text file, and among the strings there is one: "15121 ♥☺020 000000/=n531☻".
I use .Contain() method to spot ♥☺☻ symbols in the string, but it doesn't recognize them. For ♥,☺,☻ I also tried \u2665, \u263a, \u263b (as arguments for .Contain()), but none of them were recognized.
Moreover, I copied the string (from console output window) and pasted it into my code to compare symbols one by one.
string s = "15121 ♥☺020 000000/=n531☻"; // the same with "15121 \u2665\u263a020 000000/=n531\u263b"
for (int j = 0; j < s.Length; j++)
{
Console.WriteLine($"{line[j]} == {s[j]}: {line[j].Equals(s[j])}");
}
This is what I got:
What may be wrong and how do I recognize those symbols?
UPDATE: The input file I read strings from is a usual text file, and the strings inside looks like these (txt opened in Notepad):
As you can see, there is THE string among the others.
I don't use any encoding when reading the txt, and to specify how I do read the file and what the line is, here is my code:
string[] lines = File.ReadAllLines(path + target_file_name);
var list = new List<string>(lines);
for (int i = 0; i < list.Count; i++)
{
string line = list[i];
if (line.Length > 21)
{
Console.WriteLine(line);
if (line.Contains("/=n")) //used just to catch THE string
{
var line_b = Encoding.Unicode.GetBytes(line);
Console.WriteLine($"{line_b} : line = {line}");
foreach (byte m in line_b)
{
Console.Write(m + " ");
}
string s = "AAXX 15121 ♥☺020 000000/=n531☻";
Console.WriteLine();
var s_b = Encoding.Unicode.GetBytes(s);
Console.WriteLine($"{s_b} : s = {s}");
foreach (byte n in s_b)
{
Console.Write(n + " ");
}
Console.WriteLine();
for (int j = 0; j < s.Length; j++)
{
Console.WriteLine($"{line[j]} == {s[j]}: {line[j].Equals(s[j])}");
}
}
Reading all the lines from txt and converting them to List is a must for me. Thus, the line is a string line from initial txt file.
I have dumped the bytes of the inout text string var b = Encoding.Unicode.GetBytes(line); and compare with my literal (#pm100), and here is the result. Not quite sure what it does give me:
I'm sorry, I'm not willing to publish my code, and I may not understand some of your suggestions for I'm not very proficient in C# (and coding in general). So I would appreciate any further help as it is, if possible.
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.
For a homework assignment I have to create a very simplified assembler for MIPS code.
So we take in an input file of MIPS instruction then output a file with the associated binary for the input code. Each line of code must be mapped to a "memory" location which is just a hexadecimal value in front of the line, but we add/assign this "memory".
Therefore, what I would like to do is read in each line from a text file and at the front I would like to append a value (starting memory address in hex + (line number * 4.) Then I would like to re-read the file. If I need to read the whole file in, create a new file with the memory assigned, then read that file that's fine but I imagine probably unneccesary.
Our professor suggested a list, so here's what I have so far:
Console.WriteLine("Please enter the path to the input file:");
string inp = Console.ReadLine();
Console.WriteLine("Please enter the name of the new file:");
string otp = Console.ReadLine();
StreamReader inputFile = new StreamReader(inp);
StreamWriter outputFile = new StreamWriter(otp);
List<string> fileContents = new List<string>();
while ((inp = inputFile.ReadLine()) != null)
fileContents.Add(inp);
So my question is: How do I add a string to the beginning of each item in that list (fileContents)?
Edit:
Followup on this: I have managed to do all of this so far, I've brought in my whole document, mapped memory locations to each line, etc. However, I need to further edit some of the lines that are in the list "inputLines" by deleting some information from them.
The format will always be [0] Memory Address [1] Label or, if no label in this line then registers, operations, etc. [2]-[?] registers, operations, etc.
Once I've mapped my memory to each line, any line that has a label I want to put into a dictionary with the index as the label and the memory address as the value contained, then get rid of the label. So - how do I delete that information from any line that contains it?
//go through each line, if any line's first "token" is a label,
//put it in the dictionary as the index with the memory address as the value
//delete the label from the line
for (int i = 0; i < inputLines.Length; i++)
{
string[] token = inputLines[i].Split(new char[] { ' ', ',', '(', ')', ':' }, StringSplitOptions.RemoveEmptyEntries);
string possibleLabel = token[1];
if (opcodes.ContainsKey(possibleLabel) == false)
{
labeltable.Add(possibleLabel, token[0]);
//at this point I want to delete the possibleLabel from the inputLines[i] and not deal with it anymore.
}
}
That does correctly map to my dictionary, so not worried about that part.
You could use StringBuilder as a optimization of Faisal's code, otherwise its perfect for your needs
Console.WriteLine("Please enter the path to the input file:");
string inp = Console.ReadLine();
Console.WriteLine("Please enter the name of the new file:");
string otp = Console.ReadLine();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
string inputLines = System.IO.File.ReadAllLines(inp);
for (int i = 0; i < inputLines.Length; i++)
sb.Append("Some Text" + inputLines[i] + Environment.NewLine);
File.WriteAllText(otp, sb.ToString())
var inputLines = File.ReadAllLines(inputFilePath);
for (int i=0; i<inputLines.Length; i++)
inputLines[i] = "Some Text" + inputLines[i];
Assuming your prefixes are in another list
var prefixes = new List<string>(/* som values */);
var ix = 0;
var result = fileContents.Select(x => string.Join(" ", prefixes[ix++], x)).ToArray();
If you need to join on line numbers (from a dictionary)
var prefixes = new Dictionary<int, string>(); // Needs values
var result = new List<string>();
for (var i = 0; i < fileContents.Count; i++){
string prefix;
if (prefixes.TryGetValue(i, out prefix){ result.Add(string.Join(" ", prefix, fileContent[i])) }
else { result.Add(fileContent[i]);}
}
I want to create a method that reads from every line from a file. Next, it has to check between the pipes and determine if there are words that are more than three characters long, and are only numbers. In the file are strings organized like this:
What's going on {noway|that's cool|1293328|why|don't know|see}
With this sentence, the software should remove 1293328.
The resulting sentence would be:
What's going on {noway|that's cool|don't know}
Until now I am reading every line from the file and I made the functions that determine if the words between | | have to be deleted or not (checking a string like noway,that's cool, etc)
I don't know how to get the strings between the pipes.
You can split a string by a character using the Split method.
string YourStringVariable = "{noway|that's cool|1293328|why|don't know|see}";
YourStringVariable.Split('|'); //Returns an array of the strings between the brackets
What's about:
string RemoveValues(string sentence, string[] values){
foreach(string s in values){
while(sentence.IndexOf("|" + s) != -1 && sentence.IndexOf("|" + s) != 0){
sentence = sentence.Remove(sentence.IndexOf("|" + s), s.Lenght + 1);
}
}
return sentence;
}
In your case:
string[] values = new string[3]{ "1293328", "why", "see" };
string sentence = RemoveValues("noway|that's cool|1293328|why|don't know|see", values);
//result: noway|that's cool|don't know
string YourStringVariable = "{noway|that's cool|1293328|why|don't know|see}";
string[] SplitValue=g.Split('|');
string FinalValue = string.Empty;
for (int i = 0; i < SplitValue.Length; i++)
{
if (!SplitValue[i].ToString().Any(char.IsDigit))
{
FinalValue += SplitValue[i]+"|";
}
}
When I try and run my code I get the error:
Input string was not in a correct format.
I am trying to find the largest int in each line of a text file and then add them all up.
I am sure that there are no letters in this file and everything is separated by a space.
Here is my code:
int counter = 0;
string line;
List<int> col = new List<int>();
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(label3.Text);
while ((line = file.ReadLine()) != null)
{
int[] storage = new int[10000];
Console.WriteLine(line);
counter++;
string s = line;
string[] words = s.Split(' ');
for (int i = 0; i < words.Length; i++)
{
storage[i] = Convert.ToInt32(words[i]);
}
int large = storage.Max();
col.Add(large);
Console.WriteLine(" ");
foreach (int iii in col)
{
Console.WriteLine(iii);
}
int total = col.Sum();
Console.WriteLine(total);
}
file.Close();
// Suspend the screen.
Console.ReadLine();
It's possible that target string cannot be stored in a 32 bit integer. You can try parsing to ulong type. Take a look at Integral Types Table and Floating-Point Types Table.
Instead of doing Convert.ToInt32(), try int.TryParse(). It will return a bool value telling you if operation succeeded, and it has an out parameter where it will place result of parse operation. TryParse operation is also available on other numeric types if you decide you need them.
E.g.
int val;
string strVal = "1000";
if (int.TryParse(strVal, out val))
{
// do something with val
}
else
{
// report error or skip
}
I did a quick test and it is likely you get the error in the line
storage[i] = Convert.ToInt32(words[i]);
If so, make sure what you are trying to convert is an integer and not an empty string, for example.
I believe that the line in your code that can cause this error is
Convert.ToInt32(words[i]);
Now, when you're running this application in debug mode(which you probably are) in visual studio, you have a way to check what's going on in your program when the exception happens.
At the very very bottom of your screen is going to be some tabs. these tabs include your error list among other things. The ones I like to use are called "Locals" and "Watch". You can use the Locals tab.
When you click on the Locals tab, you should see a tree structure of all the local variables in your program. if you expand the words variable, you should see all the individual members of the array. you should also be able to see the variable i check the i'th member of your words array, and make sure that it's an integer, and not something else.
You're either converting out of size, or attempting to parse a return carriage '/r'
Make sure you're trimming your input.
My solution:
static void Main(string[] args)
{
int linecount = 100;
string path = #"C:\test\test.txt";
Random rand = new Random();
//Create File
StreamWriter writer = new StreamWriter(path, false);
for (int i = 0; i < linecount; i++)
{
for (int j = 0; j < rand.Next(10, 15); j++)
{
writer.Write(rand.Next() + " ");
}
writer.WriteLine("");
}
writer.Close();
//Sum File
long sum = Enumerable.Sum<string>(
(new StreamReader(path)).ReadToEnd().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries),
l => Enumerable.Max(
l.Split(' '),
i => String.IsNullOrEmpty(i.Trim()) ? 0 : long.Parse(i.Trim())
)
);
}