Word count not working when entering new line - c#

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", " ");

Related

String.IndexOf function giving incorrect position number for TextBox.Select

I found a strange behavior in indexOf functionality in my code, My string input is from read from a text file, when I search some text in the firstline of the code indexOf function correctly identify the position of the sub-string, but if I search some text in the second line it returns one character after the exact match, if I search something in the 3rd line it is returning 2 character position after the exact match, this is changing in the same pattern with every new line. I don't know why this is happening, I need to find a way to get the exact same position of the text.
My Code:
string fileContent = File.ReadAllText(filename);
string display_string = "";
txtOriginalText.Text = fileContent;
HighlightText(fileContent.IndexOf("projection"), 5, Color.Aqua);
display_string += fileContent.IndexOf("projection").ToString() + '\n';
HighlightText(fileContent.IndexOf("component"), 5, Color.LightGreen);
display_string += fileContent.IndexOf("component").ToString() + '\n';
HighlightText(fileContent.IndexOf("layer"), 5, Color.Pink);
display_string += fileContent.IndexOf("layer").ToString() + '\n';
txtModifiedText.Text = display_string;
Highlight function
private void HighlightText(int startIndex, int textLength, Color state)
{
txtOriginalText.Select(startIndex, textLength);
txtOriginalText.SelectionBackColor = state;
}
Image:
I tested this with a RichTextBox:
richTextBox1.Text = "test\r\ntest\r\ntest\r\n";
When you debug and check richTextBox1.Text after that line, its value is "test\ntest\ntest\n".
So it seems the RichTextBox removes the \r from your string (which as a Windows file content probably contains new line characters as \r\n).
As an immediate work around you should use IndexOf on txtOriginalText.Text instead of fileContent.

Using C# append text to each end of line of a flat file

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
}

RichTextbox write in place to current line

Clarification: I want to output line of text to the same "position" in a RichTextBox, replacing the previous line.
In C# Windows Forms Application trying to use RichTextBox for displaying messages. Most of the messages are appended, so that is fine but at one point in the program it has a counter, showing the amount of rows processed. For example like this:
Processed: 001 Records.
etc
well ... I don't need it to fill the RichTextBox with a thousands of lines like this:
Processed: 001 Records.
Processed: 002 Recoeds.
Instead I am trying to move the Caret to a start of the line and write the line again. Probably need to remove the previous line in a RichTextBox. Can't figure out how to always write to the same last line in RichTextBox.
I tried to use SelectionStart and ScrollToCaret() that did not work.
You could try something like this (rtb is your RichTextBox variable)
// Get the index of the last line in the richtextbox
int idx = rtb.Lines.Length - 1;
// Find the first char position of that line inside the text buffer
int first = rtb.GetFirstCharIndexFromLine(idx);
// Get the line length
int len = rtb.Lines[idx].Length;
// Select (Highlight) that text (from first to len chars)
rtb.SelectionStart = first;
rtb.SelectionLength = len;
// Replace that text with your update
rtb.SelectedText = "Processed: " + recordCount + " Records.";
No error handling added, but you could add some checks to be sure to stay inside the text buffer
One solution would be to store the current text before you start processing:
string oldText = richTextBox.Text;
for (int i = 0; i < X; i++)
{
// process stuff
richTextBox.Text = oldText + Environment.NewLine + "Processed: " + i + " Records.";
}
I believe that this method disregards the RTF data though, so you might use RichTextBox.Rtf instead.

c# how can I update just one line text in richtextbox?

how can I update just one line text in richtextbox?
String[] lines = richTextBox8.Lines;
lines[2] += " ";
richTextBox8.Lines = lines;
I am using this code part for update second line of richtextbox but it scans all my richtextbox lines and it takes many times.
so I want to update line text for 1 line.
How can I do that?
Note that you must never touch the Text or the Lines directly or all previous formatting gets messed up.
Here is a function that will solve the problem without messing up the formatting:
void changeLine(RichTextBox RTB, int line, string text)
{
int s1 = RTB.GetFirstCharIndexFromLine(line);
int s2 = line < RTB.Lines.Count() - 1 ?
RTB.GetFirstCharIndexFromLine(line+1) - 1 :
RTB.Text.Length;
RTB.Select(s1, s2 - s1);
RTB.SelectedText = text;
}
Note the in C# the numbering is zero beased, so to change the 1st line you call changeLine(yourrichTextBox, 0, yourNewText);
To only modify (not replace) the line you can simply access the Lines property; just make sure never to change it!
So to add a blank to the 2nd line you can write:
changeLine(yourrichTextBox, 1, yourrichTextBox.Lines[1] + " ");

C# : Printing variables and text in a textbox

I need to know the command that I can print a sentence like "the item Peter at row 233 and column 1222 is not a number " .
I far as now I have made this:
string[] lineItems = (string[])List[]
if (!Regex.IsMatch(lineItems[0], (#"^\d*$")))
textBox2.Text += " The number ,lineItems[0], is bigger than
10 " + Environment.NewLine;
I want to print the array fields that have error. So if it finds something it will print it.
I made a code that correctly prints that there is an error on this line of the array, but I cant print the item of the array.
I need to have an Environment.NewLine because I will print many lines.
Thanks ,
George.
foreach (int lineNumber in lineItems)
{
if (lineNumber > 10)
textBox2.Text += "The number " + lineNumber + " is bigger than 10\n";
}
Something like this should work, (I have not checked the c# code, I am working on a mac at the moment)
TextBox2.Text="This is FirstLine\nThis is Second Line";
The code is not compilable absolutely, but I may be understand what you're asking about.
If you are asking about how to compose the string of text box, by adding new strings to it, based on some desicional condition (regex), you can do folowing, pseudocode:
StringBuilder sb = new StringBuidler();
if (!Regex.IsMatch(lineItems[i], (#"^\d*$")))
sb.Append(string.Format(The number ,{0}, is bigger than 10, lineItems[i]) + Environment.NewLine);
textBox2.Text = sb.ToString();
If this is not what you want, just leave the comment, cause it's not very clear from post.
Regards.

Categories