So I have a program that does a for loop, reading every character one by one and replacing it with a four digit number correlating to that particular letter using a case statement.
My problem is it is not reading NewLine characters ('\n') and I don't know how to fix this.
Here is my code:
for (int i = 0; i < inputTextBox.Text.Length; i++)
{
//Encryption
switch (inputTextBox.Text[i])
{
// I got rid of the rest of the cases
// as they are not relevant
case '\n':
encryptedString = encryptedString + "8024";
break;
}
}
and since it does not accept the new line as a character, it doesn't add it to the encryptedString.
This might seem like a duplicate question but the other posts that I found were actually in completely different situations.
EDIT ----------------------------------------------------------------------------------------------------------------------------
So after debugging, it turns out it is actually reading the '\n' it is just not writing it to the string when decoding it.
here's the code for the decoding section:
for (int i = 0; i < readString.Length; i = i + 4)
{
//Decryption
switch (readString.Substring(i, 4))
{
case "8024":
decryptedString = decryptedString + "\n";
break;
}
}
inputTextBox.Text = decryptedString;
So it is reaching the "decryptedString = decryptedString + "\n";" line it is just not adding a new line to the string for some reason. I have also tried '\n' instead of "\n" just to be sure.
I replaced the "\n" when decoding the newlines with a "System.Environment.NewLine" and it fixed the problem.
Try first replace new lines with this Regex.Replace(inputTextBox.Text, "\r\\D\n?|\n\\D\r?", "\n");
EDIT: Are you sure it didn't worked?
For examlpe if encryptedstring is:
First string
second
3rd
fourth
Using this:
encryptedString = Regex.Replace(encryptedString, "\r\\D\n?|\n\\D\r?", "\n");
encryptedString = encryptedString.Replace("\n", "8024");
Will make encryptedString = First string8024second80243rd8024fourth is that what you wanted?
Related
So in this example I attempted to make a program that inserts a "*" in between every character that is in a certain textbox (textBox1). Though I'm having trouble figuring it out. Yes I have looked around on stack-overflow already, nothing seems to relate/work with what I'm trying to do.
Here's the code I have currently:
for (int i = 1; i <= textBox1.Text.Length; i += 1)
{
textBox2.Text = textBox1.Text.Insert(i, "*");
i++;
}
Here is a picture of what this current code does:
pretty easy to do like...
textBox2.Text = string.Join('*', textBox1.Text.ToCharArray())
You're doing a whole lot of unnecessary things. I'm using two strings instead of text boxes as I'm on Console, but the idea is the same.
var tb1Text = "hello";
var tb2Text = string.Empty;
foreach (var ch in tb1Text)
{
tb2Text += ch + "*";
}
tb2Text = tb2Text.TrimEnd(new char[] { '*' });
We iterate through the string (because a string is essentially an array of char), and add it to the tb2Text along with a trailing *. If you don't want a trailing * at the very end, use the last line of code, otherwise get rid of it.
Result
tb1Text = hello
And
tb2Text = h*e*l*l*o
How to I append text to end of a line in a flat file using c#? Basically, I'd like to append row numbers at the end of each line.
Just a quick refactor of MasterXD's solution:
var linesInText = stringWithText.Split(Environment.NewLine);
StringBuilder stringWithRowNumbers = new StringBuilder();
var row = 1;
foreach (var line in linesInText)
{
stringWithRowNumbers.Append(line);
stringWithRowNumbers.Append(row++);
stringWithRowNumbers.Append(Environment.NewLine);
}
string result = stringWithRowNumbers.ToString();
Using StringBuilder for this is going to perform much better than simple string concatenation and is considered a best practice in this use case.
Here is a quick one line version using Linq's Enumerable.Select with index and String.Join Method (String, String[]) to rebuild the lines.
string path = "Path to your flat file";
var numberedText = String.Join(Environment.NewLine, File.ReadAllLines(path).Select((line, index) => string.Join(" ", line.Trim(), index + 1)));
Console.WriteLine(numberedText);
The resulting string will have row numbers at the end of each line.
By flat file i suppose you mean a normal text file?
Firstly you'd want to split a piece of text into it's lines. This is done by the following means:
string[] linesInText = stringWithText.Split('\n');
The character \n represents a new line. So everytime a 'new line' is present, split there. The the fucction Split seperates a string into parts, where the seperator is given as the input. The parts will then be made into a string array. In this case, all the lines in the text or string willbe turned into an array.
Now you'd want to add the numbers to the end of each line. This can be done in the following way:
string stringWithRowNumbers = "";
for (int i = 0; i < linesInText.Length; i++) // Go through all lines
{
stringWithRowNumbers = linesInText[i] + "YourNumbers" + "\n"; // The old/first line + your numbers + new line
}
Now you should have a string with numbers in the end of all lines.
I hope this helps.
EDIT: I just realized you asked for row numbers. Here's the correct code.
string stringWithRowNumbers = "";
for (int i = 0; i < linesInText.Length; i++) // Go through all lines
{
// The space is intentional. If there is no space, then the number will not have any space between itself and the line
stringWithRowNumbers = linesInText[i] + " " + (i + 1) + "\n"; // The old/first line + row number + new line
}
I've been looking at other stack overflow articles regarding similar issues when it comes to word count in C#, but none have helped me when it comes to the pickle I've encountered.
I have a textbox that inputs text from a text file. The text is split into three lines by me pressing the enter button to create a new line in a text file. The text reads:
It's a test to see "if" the
application_for Top Image Systems
actually work. Hopefully it does work.
Now as you can see there should be 17 words, however my word count only says 15. I have realized after a bit of trial and error that the issue must be the fact it's in a new line. Every time it goes to a new line, it thinks the last word of the previous line and the first word of the new line are together as a word (or that's what I think the program is thinking).
My question is with the code I have below, how can I get to recognize that if there is a new line, that it should split the words like a space?
Below is my code:
string nl = System.Environment.NewLine;
//Missing Code to read text file which I don't need to include in this example
do
{
textLine = textLine + txtReader.ReadLine();
}
//Read line until there is no more characters
while (txtReader.Peek() != -1);
//seperate certain characters in order to find words
char[] seperator = (" " + nl).ToCharArray();
//number of words
int numberOfWords = textLine.Split(seperator, StringSplitOptions.RemoveEmptyEntries).Length;
txtReader.ReadLine(); strips your newline away.
From the msdn:
The string that is returned does not contain the terminating carriage return or line feed.
so you have to add it manually (or just add a space)
textLine = textLine + txtReader.ReadLine() + " ";
consider using the StringBuilder class for repeated concatination of strings.
Edit:
To get the character count as if the spaces were never added, do:
int charCount = textLine.Length - lineCount;
where lineCount an integer that you increment every time you add a space in your do-while loop:
int lineCount = 0;
do
{
textLine = textLine + txtReader.ReadLine();
lineCount++;
}
I'm a bit of a beginner myself, sorry if this is not a great answer, but I've just done a bunch of text stuff in c# and I'd probably approach by replacing the line breaks which will show up as "\n" or "\r" in your original string with a space, " " - something like:
nl = nl.Replace("\r", " ");
Okay so I'm trying to make a 'console' like text box within a form, however once you reach the bottom, instaid of being able to scroll up, it will just delete the top line, Im having some difficulties.
So far, when it gets to bottom it deletes the top line, however only once, it just carries on as normal. Here is my function:
StringBuilder sr = new StringBuilder();
public void writeLine(string input)
{
string firstline = "";
int numLines = Convert.ToString(sr).Split('\n').Length;
if (numLines > 15) //Max Lines
{
sr.Remove(0, Convert.ToString(sr).Split('\n').FirstOrDefault().Length);
}
sr.Append(input + "\r\n");
consoleTxtBox.Text = Convert.ToString(sr) + numLines;
}
Would be great if someone could fix this, thanks
Lucas
First, what's wrong with your solution: the reason it does not work is that it removes the content of the line, but it ignores the \n at the end. Adding 1 should fix that:
sr.Remove(0, Convert.ToString(sr).Split('\n').FirstOrDefault().Length+1);
// ^
// |
// This will take care of the trailing '\n' after the first line ---+
Now to doing it a simpler way: all you need to do is finding the first \n, and taking substring after it, like this:
string RemoveFirstLine(string s) {
return s.Substring(s.IndexOf(Environment.NewLine)+1);
}
Note that this code does not crash even when there are no newline characters in the string, i.e. when IndexOf returns -1 (in which case nothing is removed).
You can use the Lines property from the TextBox. This will get all the lines in the TextBox, as an array, then create a new array that doesn't include the first element (Skip(1)). It assigns this new array back to the textbox.
string[] lines = textBox.Lines;
textBox.Lines = lines.Skip(1).ToArray();
A simple alternative: you could split the string by Environment.NewLine and return all but the first:
public static string RemoveFirstLine(string input)
{
var lines = input.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
return string.Join(Environment.NewLine, lines.Skip(1));
}
Demo
you can remove this line
var lines = lines.Remove(0, lines.ToString().IndexOf(Environment.NewLine));
Most solutions does not seem to take into account the fact that Enviroment.NewLine can consist of multiple characters (len > 1).
public void RemoveFirstStringFromStringBuilder()
{
var lines = new StringBuilder();
lines.AppendLine("abc");
var firstLine = lines.ToString().IndexOf(Environment.NewLine, StringComparison.Ordinal);
if (firstLine >= 0)
lines.Remove(0, firstLine + Environment.NewLine.Length);
Console.WriteLine(lines.Length);
Console.WriteLine(lines.ToString());
}
Prints out: 0 and ""
What worked for me is:
var strBuilder = new StringBuilder();
strBuilder.AppendLine("ABC");
strBuilder.AppendLine("54");
strBuilder.AppendLine("04");
strBuilder.Remove(0, strBuilder.ToString().IndexOf(Environment.NewLine) + 2);
Console.WriteLine(strBuilder);
Solution with +1 didn't work for me, probably because of EOF in this context being interpreted as 2 chars (\r\n)
Hi I `m trying to grep through file and count number of lines, maximum number of spaces per line, and longest line.
How I can determine "/n" character if i iterate char by char trough given file?
Thanks a lot.
Here is my code that I used for this:
using (StreamReader sr = new StreamReader(p_FileName))
{
char currentChar;
int current_length=0,current_MaximumSpaces=0;
p_LongestLine=0;
p_NumOfLines=0;
p_MaximumSpaces=0;
while (!sr.EndOfStream){
currentChar=Convert.ToChar(sr.Read());
current_length++;
if(Char.IsWhiteSpace(currentChar) || currentChar==null){
current_MaximumSpaces++;
}
if(currentChar == '\n'){
p_NumOfLines++;
}
if(current_length>p_LongestLine){
p_LongestLine=current_length;
}
if(current_MaximumSpaces>p_MaximumSpaces){
p_MaximumSpaces=current_MaximumSpaces;
}
current_length=0;
current_MaximumSpaces=0;
}
sr.Close();
}
if(currentChar == '\n')
count++;
You do not need to go character by character: for your purposes, going line-by-line is sufficient, and you get the .NET to deal with system-dependent line breaks for you as an added bonus.
int maxLen = -1, maxSpaces = -1;
foreach ( var line in File.ReadLines("c:\\data\\myfile.txt")) {
maxLen = Math.Max(maxLen, line.Length);
maxSpaces = Math.Max(maxSpaces, line.Count(c => c == ' '));
}
EDIT: Your program does not work because of an error unrelated to you checking the '\n': you are zeroing out the current_length and current_MaximumSpaces after each character, instead of clearing them only when you see a newline character.
Try comparing to Environment.NewLine
bool is_newline = currentChar.ToString().Equals(Environment.NewLine);
I'm guessing that you newline is actually \r\n (non Unix) ending. You'll need to keep track of the previous/current char's and look for either \r\n or Environment.NewLine.