How to count the number of words in a string? [duplicate] - c#

This question already has answers here:
Count how many words in each sentence
(8 answers)
Closed 8 years ago.
I want to count the number of words in a string.
Like if given a string:
string str = "Hello! How are you?";
thn the output will be:
Number of words in string “Hello! How are you?” is 4.
I'm using for loop, and these are my current codes.
string wordCountStr = "";
int noOfWords = 0;
private void btn_Computate4_Click(object sender, EventArgs e)
{
wordCountStr = tb_Qns4Input.Text.ToString(); //tb_Qns4Input is a textbox.
for (int i = 0; i< wordCountStr.Length; i++)
{
//I don't know how to code here.
}
lbl_ResultQns4.Text = "Number of words in string " + wordCountStr + " is " + noOfWords;
}
Oh yes, I'm using Microsoft Visual Studio 2013 for my work. So the codes are under a button click event.
Addition:
What are the different methods to code using 'foreach', 'for loops', 'do/while' loops & 'while' loops?
I can only use these 4 loops to my work.
I have solved this question by using these codes:
string wordCountStr = "";
int noOfWords = 0;
private void btn_Computate4_Click(object sender, EventArgs e)
{
wordCountStr = tb_Qns4Input.Text.ToString();
foreach (string sentence in wordCountStr.TrimEnd('.').Split('.'))
{
noOfWords = sentence.Trim().Split(' ').Count();
}
lbl_ResultQns4.Text = "Number of words in ''" + wordCountStr + "'' is " + noOfWords;
}

Assuming perfect input you can simply split on the space and then get the Length of the resulting array.
int count = wordCountStr.Split(' ').Length;

Related

I just get System.IndexOutOfRangeException [duplicate]

This question already has answers here:
Reverse word of full sentence
(20 answers)
Closed 2 years ago.
I've been tried to do an algorithm that ask for a sentence and put the words backwards, for example if I insert "Cookies and milk" it would give back "milk and Cookies", but it gives me System.IndexOutOfRangeException in the second for. Please help
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string sentence;
string spac = " ";
char[] phr;
char space = char.Parse(spac);
Console.WriteLine("Write a sentence");
sentence = Console.ReadLine();
phr = sentence.ToCharArray();
for (int i = phr.Length-1; i >= 0; i--)
{
if (phr[i] == space)
{
for (int j = i++; phr[j] != phr.Length-1 || phr[j]!=space; j++)
{
Console.WriteLine(phr[j]);
}
}
}
}
}
}
You can split a string into an array based on any character. If you split by space you can keep the words intact. Do this, then reverse the order, and join it again.
string sentence = "Cookies and Milk";
string wordsReversed =
string.Join(" ",
sentence.Split(' ').Reverse()
);
Console.WriteLine(wordsReversed); // "Milk and Cookies"

Hey I need more information about this code [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
private void Button4_Click(object sender, EventArgs e) {
string start = Directory.GetCurrentDirectory() + #"\Sav1.txt";
using(var streamReader = new StreamReader(start)) {
string line = streamReader.ReadLine();
int[] values = line.Split(' ').Select(int.Parse).ToArray();
Array.Sort(values);
Array.Reverse(values);
for (int i = 0; i < values.Length; i++) {
richTextBox4.AppendText(values[i] + " ");
}
}
}
Hey guys I need more information about this code. Could anyone explain me how it works. I mostly googled it so dont know how it works. Also I have added .txt file and got access to first row, but i need to get into 7 and 8 row. There's just random numbers in that .txt file.
Ok so there's a better way to do this. StreamReader has a .Peek() method that is extremely useful for reading to the end of a file. Basically the only thing you're missing is a way to loop through each line in your file.
Start with your using statement.
using(var streamReader = new StreamReader(start)) {...
//Using statement is a way for you to close your stream after the work
//is completed. This is why you need to get a loop inside of here.
Use a loop to read to the end of a file.
This part is what I'd change in your code. Your Using statement will not loop. You have to tell it to loop. Peek() returns -1 or the next character to be read. So you can use this to your advantage to check if you want to read to the end of file. Review the documentation here. https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader.peek?view=netframework-4.8
while(streamReader.Peek() > -1)
{...
Then you can split to your array per line by simply reading in each or splitting to a character.
int[] values = streamReader.Readline().Split(' ');
Finally you can do the remainder of your code.
for (int i = 0; i < values.Length; i++) {
richTextBox4.AppendText(values[i] + " ");
}
To break down exactly what is going on in your code. Read each comment line by line to get a basic understanding.
//Button Click Event
private void Button4_Click(object sender, EventArgs e) {
//Finding your file and assigning it as a string.
string start = Directory.GetCurrentDirectory() + #"\Sav1.txt";
//Using a `using` statement and creating a new streamReader that will look
//for the string that you created above to find the file. The using block
//will properly close the streamreader when the work is done.
using(var streamReader = new StreamReader(start)) {
//StreamReader.ReadLine() will read the FIRST line, no loop here.
//This is why your code only reads one.
string line = streamReader.ReadLine();
//Splitting to an array.
int[] values = line.Split(' ').Select(int.Parse).ToArray();
//Sorting array.
Array.Sort(values);
//Reversing the array.
Array.Reverse(values);
//Looping through the array based on count.
for (int i = 0; i < values.Length; i++) {
richTextBox4.AppendText(values[i] + " ");
}
}
}
If you're attempting to only get rows 7, 8, 9, etc.. within your for loop at the very end of your code do the following.
//Looping through the array based on count.
for (int i = 0; i < values.Length; i++) {
//This will only append rows 7-9. Keep in mind an array is a 0 based
//index. Meaning row 7 is actually array element 6. Row 9 is actually
//array element 8.
if(i > 5 && i < 9){
richTextBox4.AppendText(values[i] + " ");
}
}
}
}
So my current code looks like this:
private void Button4_Click(object sender, EventArgs e)
{
string start = Directory.GetCurrentDirectory() + #"\Sav1.txt";
using (var streamReader = new StreamReader(start))
{
while (streamReader.Peek() > -1)
{
string[] values = streamReader.ReadLine().Split(' ');
Array.Sort(values);
Array.Reverse(values);
for (int i = 0; i < values.Length; i++)
{
richTextBox4.AppendText(values[i] + " ");
}
}
}

Use the "new" keyword to create an object instance [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
Is someone able to help me out with the following please, I'm trying to split data from an input file (2 pieces of data per line, separated by either of the delimiters specified in the code below). To do this I have declared the string array 'split input', however when I run the program I get a runtime error (screenshot) with the split input line inside the while loop highlighted in yellow. I can't see what I am doing wrong, I'm copying sample code which seems to be working fine :(
NB - the messageBox line below the yellow is just for my testing to prove the split worked
private int DetermineArraySize(StreamReader inputFile)
{
int count = 0;
while (!inputFile.EndOfStream)
{
inputFile.ReadLine();
count++;
}
return count;
}
private void ReadIntoArray(StreamReader inputFile, string[] gameArray, int[] revArray)
{
string rawInput;
string[] splitInput = new string[2];
int count = 0;
char[] delimiters = {'=', '#',};
while (!inputFile.EndOfStream || count < gameArray.Length)
{
rawInput = inputFile.ReadLine();
{
splitInput = rawInput.Split(delimiters);
MessageBox.Show(splitInput[0] + " // " + splitInput[1]);
count++;
}
}
}
private void rdGameSalesForm_Load(object sender, EventArgs e)
{
StreamReader inputFile = File.OpenText("GameSales.txt"); //Open Input File
int arraySize = DetermineArraySize(inputFile); //Use input file to determine array size
string[] gameTitle = new string[arraySize]; //Declare array for GameTitle
int[] revenue = new int[arraySize]; ///Declare array for Revenue
ReadIntoArray(inputFile, gameTitle, revenue);
Thanks for your help
Just add check on null.
ReadLine Method returns null if the end of the input stream is reached. It is possible because you check !inputFile.EndOfStream or count < gameArray.Length. So in the second condition has a possibility to get null when input filre reading
while (!inputFile.EndOfStream || count < gameArray.Length)
{
rawInput = inputFile.ReadLine();
if(rawInput !=null)
{
splitInput = rawInput.Split(delimiters);
MessageBox.Show(splitInput[0] + " // " + splitInput[1]);
}
}
Check for null instead of end of stream.
while((rawInput = Inputfile.ReadLine()) != null)
{
splitInput = rawInput.Split(delimiters);
MessageBox.Show(...);
}

write a loop that prints a number of lines the user entered into the text box, this is using c# windows application

write a loop that prints a number of lines the user entered into the text box
for example, this is using c# windows application
user inputs 10, then in another textbox counts from 0 to 10 on different lines
Result
0 \r\n
1 \r\n
2 \r\n
3 \r\n
4 \r\n
5 \r\n
6 \r\n
7 \r\n
8 \r\n
9 \r\n
10 \r\n
i have tried to incorporate a for loop and for each but it is only printing out one value, and i have to go into the array and print each iteration of the array like so textboxOutput.text = Array[0] + Array[1] , but i want it to print out all of the list without accessing the single ints in the array
private void button1_Click(object sender, EventArgs e)
{
string input = textBox1.Text;
int Number;
bool Anumber = Int32.TryParse(input, out Number);
int newNumber = Number;
int[] List = new int[newNumber];
for (int i = 0; i < List.Length; i++ )
{
List[i] = i;
//textBox2.Text =List[0] + "\r\n" + List[1] + "\r\n" + List[2];
}
foreach (int num in List)
{
textBox2.Text = num.ToString() ;
}
}
}
}
I have managed to figure out my own question
private void button1_Click(object sender, EventArgs e)
{
int OutputNumber;
bool number = Int32.TryParse(inputtxt.Text, out OutputNumber);
string[] array = new string[OutputNumber];
int put = 0;
for (int i = 0; i < array.Length; i++)
{
array[i] = put.ToString();
put++;
string result = ConvertStringArrayToString(array);
string result1 = result + OutputNumber.ToString();
outputtxt.Text = result1;
}}
static string ConvertStringArrayToString(string[] array)
{
StringBuilder buildingstring = new StringBuilder();
foreach (string value in array)
{
buildingstring.Append(value);
buildingstring.Append("\r\n");
}
return buildingstring.ToString();
}
I have gone around a different way, by creating a string array adding each value to the string array and using a separate function to join all of the string array data together and separating each value with a return

How to count characters in RichTextBox using C#

I am new to programming and having problems making a simple code for character counter for a button. I've somehow managed to code a line together that actually counts words. here it is:
private void button_add_Click(object sender, EventArgs e)
{
string count = richTextBox.Text;
label_info.Text = "Word count is " + (count.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Length).ToString();
//Trying to add a new character count down here
// label_info.Text = "Character count is " + ....code ...;
}
Any advice would be appreciated.
EDIT: Thanks to you all i got my answer here:
private void button_add_Click(object sender, EventArgs e)
{
string count = richTextBox.Text;
label_info.Text = "Word count is " + (count.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Length).ToString();
label_info.Text = "\nCharacter count is " + richTextBox.Text.Lenth;
}
Try using string's Length property.
label_info.Text = label_info.Text + "\nCharacter count is " + richTextBox.Text.Lenth;
You are splitting the string on each space and counting the length of the resulting array. If you want the length of the string (with whitespace etc.) you can do this:
label_info.Text = "Character count is " + count.length;
If you don't want the whitespace you can do this:
label_info.Text = "Character count is " + count.Replace(" ", "").length;
You don't have to write a complex code. You can count characters using length property. See below sample codes. In it we use a Textbox and a Label, Label shows the count of characters entered in the textbox.
void textBox1_TextChanged(object sender, EventArgs e)
{
lablename.Text = textboxname.Text.length.Tostring();
}
I have also created its video tutorial. Watch it on YouTube
string a = richTextBox1.Text;
label2.Text = a.Length.ToString();

Categories