I am learning c#, and have home works to make simple dictionary in console aplication.
I wrote all the code and it should work good but in one of the for loops the program throws Error:System.IndexOutofRange.
I tried all I know (I am only beginner so I dont know much) but it always gives the error.
The main idea of the program is the user must enter how much words he wishes to use then enter the words in the his language (my is Hebrew so in the program is Hebrew) and in English and it save the words in two deffernt Arrays but in same index. Then the program ask the user to enter sentence in his language and then the program runs on the sentence finds the words (each time the program see space it starts a new word), then with another for loop it looks in the Hebrew Array and if it finds match place the word that in the same index but in the English Array, and if not found it writes the original word.
static void Main(string[] args)
{
Console.WriteLine("Enter the number of words you wish to use");
int wordsNumber = int.Parse(Console.ReadLine());
string[] hebrew = new string[wordsNumber];
string[] english = new string[wordsNumber];
for (int i = 0; i < wordsNumber; i++)
{
Console.WriteLine("Enter word in Hebrew.");
hebrew[i] = Console.ReadLine();
Console.WriteLine("Now enter the translate of {0} in English.",hebrew[i]);
english[i] = Console.ReadLine();
}
Console.WriteLine("Now enter the sentence that you want to translate..and press ENTER");
string searchSentence = Console.ReadLine();
string translateWord = "";
string result = "";
while(searchSentence != "stop")
{
for (int i = 0; i < searchSentence.Length;i++ )
{
translateWord = "";
while ((searchSentence[i] == ' ')&&(searchSentence.Length > i))//Skip the spaces in the start of the sentence
i++;
while ((searchSentence[i] != ' ') && (searchSentence.Length > i))//Here is the problem when with the OutOfRnge
{
translateWord += searchSentence[i];
i++;
}
for(int j = 0;j<hebrew.Length ;j++)
{
if (translateWord == hebrew[j])
{
result += english[j];
}
else
{
result += translateWord[i];
}
result += " ";
}
}
Console.WriteLine(result);
Console.WriteLine("Enter new sentence for translate or enter 'stop' to EXIT the programm");
searchSentence = Console.ReadLine();
}
while ((searchSentence[i] != ' ') && (searchSentence.Length > i))
Consider that the way you are used to read (right-to-left in your neck of the woods) is affecting the way you write code. This code is backwards, both in the order of the && operands and in the Length test. And thus doesn't take advantage of the short-circuiting behavior of the && operator. Probably difficult to unlearn, something you'll have to work on.
Avoid this exception with:
while ((i < searchSentence.Length) && (searchSentence[i] != ' '))
Which ensures that searchSentence[i] cannot throw the IndexOutOfRangeException.
Your code was very confusing and it would be hard to tell where the error was.. However you would be better off constructing a dictionary full of translations and then using that. I have left out error handling for you to expand upon but here is an example of doing the exact same - but with a dictionary
Dictionary<string, string> words = new Dictionary<string, string>();
Console.WriteLine("Enter the number of words you wish to use");
int wordsNumber = int.Parse(Console.ReadLine());
for (int i = 0; i < wordsNumber; i++)
{
Console.WriteLine("Enter word in Hebrew.");
string hebrew = Console.ReadLine();
Console.WriteLine("Now enter the translate of {0} in English.", hebrew);
string english = Console.ReadLine();
words.Add(hebrew, english);
}
Console.WriteLine("Now enter the sentence that you want to translate..and press ENTER");
string searchSentence = Console.ReadLine();
string[] splitSentence = searchSentence.Split(new char[]{' '});
string result = "";
foreach (string s in splitSentence)
result += string.Format("{0} ", words[s]);
Console.WriteLine(result);
Console.ReadLine();
Looking at
while(searchSentence != "stop")
{
for (int i = 0; i < searchSentence.Length;i++ )
{
translateWord = "";
while ((searchSentence[i] == ' ')&&(searchSentence.Length > i))//Skip the spaces in the start of the sentence
i++; //updated here and used on nex line when i could be greater than SearchSentence.Length now
while ((searchSentence[i] != ' ') && (searchSentence.Length > i))//Here is the problem when with the OutOfRnge
{
translateWord += searchSentence[i];
i++; // updated here
}
for(int j = 0;j<hebrew.Length ;j++)
{
if (translateWord == hebrew[j])
{
result += english[j];
}
else
{
result += translateWord[i];
}
result += " ";
}
}
You increment i inside the for loop. If it becomes equal to or greater than searchSentence.Length then you use it it will throw the error you get
edit to fix make this change from this
for (int i = 0; i < searchSentence.Length;i++ )
{
translateWord = "";
while ((searchSentence[i] == ' ')&&(searchSentence.Length > i))//Skip the spaces in the start of the sentence
i++;
while ((searchSentence[i] != ' ') && (searchSentence.Length > i))//Here is the problem when with the OutOfRnge
{
translateWord += searchSentence[i];
i++;
}
for(int j = 0;j<hebrew.Length ;j++)
{
if (translateWord == hebrew[j])
{
result += english[j];
}
else
{
result += translateWord[i];
}
result += " ";
}
}
to this
for (int i = 0; i < searchSentence.Length;i++ )
{
if(((searchSentence[i] != ' ')&&(searchSentence.Length > i)))
{
while ((searchSentence[i] != ' ') && (searchSentence.Length > i))//Here was the problem when with the OutOfRnge
{
translateWord += searchSentence[i];
i++; // updated here
if(i>=searchSentence.Length)
{
break;
}
}
if(i>=searchSentence.Length)
for(int j = 0;j<hebrew.Length ;j++)
{
if (translateWord == hebrew[j])
{
result += english[j];
}
else
{
result += translateWord[i];
}
result += " ";
}
}
}
Related
I am making a program for a hangman game that picks a random word from a text file of words and then asks the user to guess each letter of the word. Each letter in the word is displayed with an asterisk and when the user makes a correct guess the actual letter is then displayed. After the word is guessed it will then display the number of times missed and ask the user if they want to guess another word.
I have the asterisks hard coded but I would like the asterisks to be the same length of the random word chosen from the text file. I am not sure how I would do this
Any help would be appreciated.
static void Main(string[] args)
{
char[] guessed = new char[26];
char[] testword = "******".ToCharArray();
char[] word = RandomLine().ToCharArray();
char[] copy = word;
char guess;
char playAgain;
int amountMissed = 0, index = 0;
Console.WriteLine(testword);
do
{
Console.WriteLine("I have picked a random word on animals");
Console.WriteLine("Your task is to guess the correct word");
while (testword != word)
{
Console.Write("Please enter a letter to guess: ");
guess = char.Parse(Console.ReadLine());
bool right = false;
for (int j = 0; j < copy.Length; j++)
{
if (copy[j] == guess)
{
Console.WriteLine("Your guess is correct.");
testword[j] = guess;
guessed[index] = guess;
index++;
right = true;
}
}
if (right != true)
{
Console.WriteLine("Your guess is incorrect.");
amountMissed++;
}
else
{
right = false;
}
Console.WriteLine(testword);
}
Console.WriteLine($"The word is {copy}. You missed {amountMissed} times.");
Console.WriteLine("Do you want to guess another word? Enter y or n: ");
playAgain = char.Parse(Console.ReadLine());
} while (playAgain == 'y' || playAgain == 'Y');
Console.WriteLine("Good-Bye and thanks for playing my Hangman game.");
}
public static string RandomLine()
{
try
{
// store text file in an array and return a random value
string[] lines = File.ReadAllLines("C:\\Intel\\Advanced1.csv");
Random rand = new Random();
return lines[rand.Next(lines.Length)];
}
catch (Exception e)
{
Console.WriteLine("The file could not be read");
Console.WriteLine(e.Message);
}
}
To display the coded word (with asterisks) with same length as word, you could use
char[] testword = new string('*',word.Length).ToCharArray();
Making few other corrections in your code
char[] guessed = new char[26];
char guess;
char playAgain;
int amountMissed = 0, index = 0;
do
{
char[] word = RandomLine().ToCharArray(); // Change :This needs to be inside the loop so that new random word could be selected user selects to continue the game
char[] testword = new string('*',word.Length).ToCharArray(); // Change : Reordered initilization of word and testword so that we could generate testword with same length as original
char[] copy = word;
Console.WriteLine(testword);
Console.WriteLine("I have picked a random word on animals");
Console.WriteLine("Your task is to guess the correct word");
while (!testword.SequenceEqual(word)) // Change : Comparison of arrays
{
Console.Write("Please enter a letter to guess: ");
guess = char.Parse(Console.ReadLine());
bool right = false;
for (int j = 0; j < copy.Length; j++)
{
if (copy[j] == guess)
{
Console.WriteLine("Your guess is correct.");
testword[j] = guess;
guessed[index] = guess;
index++;
right = true;
}
}
if (right != true)
{
Console.WriteLine("Your guess is incorrect.");
amountMissed++;
}
else
{
right = false;
}
Console.WriteLine(testword);
}
Console.WriteLine($"The word is {copy}. You missed {amountMissed} times.");
Console.WriteLine("Do you want to guess another word? Enter y or n: ");
playAgain = char.Parse(Console.ReadLine());
} while (playAgain == 'y' || playAgain == 'Y');
Console.WriteLine("Good-Bye and thanks for playing my Hangman game.");
This way:
class Program
{
static void Main(string[] args)
{
bool found = false;
string originalWord = "test";
char[] word = originalWord.ToCharArray();
char[] asteriskedWord = new string('*', word.Length).ToCharArray();
while (found == false)
{
Console.WriteLine(asteriskedWord);
string input = Console.ReadLine();
if (input.Length != 1)
{
Console.WriteLine("Your input can be only one char.");
}
else
{
char c = char.Parse(input);
for (int i = 0; i < word.Length; i++)
{
if (word[i] == c)
{
asteriskedWord[i] = c;
word[i] = '*';
int missingCharsAmount = asteriskedWord.Count(x => x == '*');
Console.WriteLine("Correct, missing " + missingCharsAmount + " chars.");
if (missingCharsAmount == 0)
{
found = true;
}
break;
}
}
}
}
}
}
So essentially I want the displayToPlayer variable have the spaces automatically added but I'm not quite sure how to achieve this.
How can I have the spaces automatically added to the hidden message without using a turn or it been added to the guessed letter tally.
Current Result:
Desired Result:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace guessingGame
{
class Program
{
static void Main(string[] args)
{
string[] quoteList = {
"NEVER GUNNA LET YOU DOWN",
/*"NEVER GUNNA RUN AROUND",
"THIS IS A TEST"*/
}; // the list of quotes that need to be guessed by the player
Random random = new Random((int)DateTime.Now.Ticks);
string quoteToGuess = quoteList[random.Next(0, quoteList.Length)];
string quoteToGuessUppercase = quoteToGuess.ToUpper();
StringBuilder displayToPlayer = new StringBuilder(quoteToGuess.Length);
for (int i = 0; i < quoteToGuess.Length; i++)
{
displayToPlayer.Append('*');
}
List<char> correctGuesses = new List<char>();
List<char> incorrectGuesses = new List<char>();
int quoteToGuessLength = quoteToGuess.Count(characters => !Char.IsWhiteSpace(characters));
int turnsLeft = quoteToGuess.Distinct().Count(characters => !Char.IsWhiteSpace(characters)) + 3;
bool quoteGuessed = false;
int lettersRevealed = 0;
string userInput;
char userGuess;
Console.WriteLine("Can you work out the quote? (you have {0} chances)", turnsLeft);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine(displayToPlayer.ToString());
Console.WriteLine();
while (!quoteGuessed && turnsLeft > 0)
{
Console.Write("Enter your letter ==>");
try
{
userInput = Console.ReadLine().ToUpper();
userGuess = userInput[0];
if (correctGuesses.Contains(userGuess))
{
Console.WriteLine("You've already tried '{0}', and it was correct!", userGuess);
continue;
}
else if (incorrectGuesses.Contains(userGuess))
{
Console.WriteLine("You've already tried '{0}', and it was wrong!", userGuess);
continue;
}
if (quoteToGuessUppercase.Contains(userGuess))
{
correctGuesses.Add(userGuess);
for (int i = 0; i < quoteToGuess.Length; i++)
{
if (quoteToGuessUppercase[i] == userGuess)
{
displayToPlayer[i] = quoteToGuess[i];
lettersRevealed++;
}
}
if (lettersRevealed == quoteToGuess.Length)
{
quoteGuessed = true;
}
turnsLeft--;
Console.Clear();
Console.WriteLine("You have guessed {0} letter(s) out of a total of {1}", lettersRevealed, quoteToGuessLength);
Console.WriteLine("You have {0} attempts remaining!", turnsLeft);
Console.WriteLine();
Console.WriteLine(displayToPlayer.ToString());
Console.WriteLine();
Console.WriteLine("Correct guess, there's a '{0}' in it!", userGuess);
Console.WriteLine();
}
else
{
incorrectGuesses.Add(userGuess);
turnsLeft--;
Console.Clear();
Console.WriteLine("You have guessed {0} letter(s) out of a total of {1}", lettersRevealed, quoteToGuessLength);
Console.WriteLine("You have {0} attempts remaining!", turnsLeft);
Console.WriteLine();
Console.WriteLine(displayToPlayer.ToString());
Console.WriteLine();
Console.WriteLine("Incorrect guess, there's no '{0}' in it!", userGuess);
Console.WriteLine();
}
}
catch (Exception e)
{
Console.WriteLine("Enter A Valid Character");
}
}
if (quoteGuessed)
{
Console.WriteLine(quoteToGuess);
Console.WriteLine("You have guessed all {0} letters out of a total of {0} Well done!!!", quoteToGuessLength);
}
else
{
Console.WriteLine("You lost! It was '{0}'", quoteToGuess);
}
}
}
}
If i understand you correctly, this will probably work
for (int i = 0; i < quoteToGuess.Length; i++)
{
displayToPlayer.Append(quoteToGuess[i] == ' ' ? ' ' : '*');
}
Its basically saying, if the character at the index of i in quoteToGuess is ' ', then add ' ', if not add '*'
?: Operator (C# Reference)
The conditional operator (?:), commonly known as the ternary
conditional operator, returns one of two values depending on the value
of a Boolean expression. Following is the syntax for the conditional
operator.
Strings and indexes
An index is the position of a Char object (not a Unicode character) in
a String. An index is a zero-based, nonnegative number that starts
from the first position in the string, which is index position zero
You can get rid of the StringBuilder and your for loop completely using System.Linq:
var displayToPlayer = new string(quoteToGuess.Select(c => c == ' ' ? ' ' : '*').ToArray());
If you get an error because Select() doesn't seem to be defined, add this on top of your file:
using System.Linq;
I want to print the string in reverse format in for loop:
Input: I'm Learning c#
Output: c# Learning I'm
No Split functions and reverse functions should be used, it has to do only with forloop.
for (int i = m.Length - 1; i >= 0; i--)
{
b[j]=a[i];
j++;
if(a[i]==' '|| a[i]==0)
{
for (int x = b.Length - 1; x >= 0; x--)
{
c[k] = b[x];
Console.Write(c[k]);
k++;
}
}
} Console.ReadKey();
You have to create an array of the words in the sentence:
var words = input.Split(' ');
Then you just loop through the above array from the end to the start:
for(int i=words.Length-1; i>=0; i--)
{
Console.Write(words[i]+" ");
}
With LINQ and string methods you can simplify it:
var reversedWords = input.Split().Reverse(); // Split without parameters will use space, tab and new-line characters as delimiter
string output = string.Join(" ", reversedWords); // build reversed words, space is delimiter
Use Stack<Queue<char>>
Hey if you want to show off your knowledge of data structures, use a queue and a stack! This makes for a very concise answer as well.
You want the sentence to be LIFO with respect to words but FIFO with respect to letters within words, so you need a stack (which are LIFO) of queues (which are FIFO). You can take advantage of the fact that a string, a queue<char>, and a stack<char> all expose IEnumerable<char> as well, so it's easy to convert back and forth; once you have all the characters ordered in your data structure, you can extract the whole thing as a character array using SelectMany(), which you can pass to a string constructor for the final answer.
This solution uses no Split() or Reverse() functions, as required.
public static string ReverseSentence(string input)
{
var word = new Queue<char>();
var sentence = new Stack<IEnumerable<char>>( new [] { word } );
foreach ( char c in input )
{
if (c == ' ')
{
sentence.Push( " " );
sentence.Push( word = new Queue<char>() );
}
else
{
word.Enqueue(c);
}
}
return new string( sentence.SelectMany( w => w ).ToArray() );
}
Usage:
public void Test()
{
var input = "I'm Learning c#";
var output = ReverseSentence(input);
Console.WriteLine(output);
}
Output:
c# Learning I'm
DotNetFiddle
Without split and reverse, I modify your logic little bit to achieve what you need
namespace MyNamespace
{
public class Program
{
public static void Main(string[] args)
{
var m="this is mystring";
var b = new char [m.Length];
var j=0;
//Your code goes here
for (int i = m.Length - 1; i >= 0; i--)
{
b[j]=m[i];
j++;
if(m[i]==' ' || i==0)
{
if(i==0)
{
b[j]=' ';
}
for (int x = b.Length - 1; x >= 0; x--)
{
Console.Write(b[x]);
}
b=new char[m.Length];
j=0;
}
}
Console.ReadKey();
Console.WriteLine("Hello, world!");
}
}
}
Input: "this is mystring"
Output: "mystring is this"
Here is a simple console application for your question
Without using Reverse and Split methods (just for loop)
class Program
{
static void Main()
{
string input = "I'm learning C#";
string[] result = new string[3];
int arrayIndex = 0;
string tempStr = "";
// Split string
for (int i = 0; i < input.Length; i++)
{
tempStr += input[i].ToString();
if (input[i] != ' ')
{
result[arrayIndex] = tempStr;
}
else
{
tempStr = "";
arrayIndex++;
}
}
// Display Result
for (int i = result.Length - 1; i >= 0; i--)
{
System.Console.Write(result[i] + ' ');
}
System.Console.WriteLine();
}
}
Press Ctrl + F5 to run the program
Output: C# learning I'm
How can I write a function which given an input string, passes back the acronym for the string using only If/Then/Else, simple String functions, and Looping syntax (not use the Split( ) function or its equivalent)?
String s_input, s_acronym
s_input = "Mothers against drunk driving"
s_acronym = f_get_acronym(s_input)
print "acronym = " + s_acronym
/* acronym = MADD */
My code is here. just looking to see if I could get better solution
static string f_get_acronym(string s_input)
{
string s_acronym = "";
for (int i = 0; i < s_input.Length; i++)
{
if (i == 0 && s_input[i].ToString() != " ")
{
s_acronym += s_input[i];
continue;
}
if (s_input[i - 1].ToString() == " " && s_input[i].ToString() != " ")
{
s_acronym += s_input[i];
}
}
return s_acronym.ToUpper();
}
Regex is the way to go in C#. I know you only wanted simple functions, but I want to put this here for any further readers who shall be directed on the right path. ;)
var regex = new Regex(#"(?:\s*(?<first>\w))\w+");
var matches = regex.Matches("Mother against druck driving");
foreach (Match match in matches)
{
Console.Write(match.Groups["first"].Value);
}
private static string f_get_acronym(string s_input)
{
if (string.IsNullOrWhiteSpace(s_input))
return string.Empty;
string accr = string.Empty;
accr += s_input[0];
while (s_input.Length > 0)
{
int index = s_input.IndexOf(' ');
if (index > 0)
{
s_input = s_input.Substring(index + 1);
if (s_input.Length == 0)
break;
accr += s_input[0];
}
else
{
break;
}
}
return accr.ToUpper();
}
Keep it simple:
public static string Acronym(string input)
{
string result = string.Empty;
char last = ' ';
foreach(var c in input)
{
if(char.IsWhiteSpace(last))
{
result += c;
}
last = c;
}
return result.ToUpper();
}
Best practice says you should use a StringBuilder when adding to a string in a loop though. Don't know how long your acronyms are going to be.
Your best way to do so would be to set up a loop to loop over every letter. If it is the first letter in the string, OR the first letter after a space, add that letter to a temp string, which is returned at the end.
eg (basic c++)
string toAcronym(string sentence)
{
string acronym = "";
bool wasSpace = true;
for (int i = 0; i < sentence.length(); i++)
{
if (wasSpace == true)
{
if (sentence[i] != ' ')
{
wasSpace = false;
acronym += toupper(sentence[i]);
}
else
{
wasSpace = true;
}
}
else if (sentence[i] == ' ')
{
wasSpace = true;
}
}
return acronym;
}
This could be further improved by checking to make sure the letter to add to the acronym is a letter, and not a number / symbol. OR...
If it is the first letter in the string, add it to the acronym. Then, run a loop for "find next of" a space. Then, add the next character. Continuously loop the "find next of" space until it returns null / eof / end of string, then return.
I'm trying to count the number of words from a rich textbox in C# the code that I have below only works if it is a single line. How do I do this without relying on regex or any other special functions.
string whole_text = richTextBox1.Text;
string trimmed_text = whole_text.Trim();
string[] split_text = trimmed_text.Split(' ');
int space_count = 0;
string new_text = "";
foreach(string av in split_text)
{
if (av == "")
{
space_count++;
}
else
{
new_text = new_text + av + ",";
}
}
new_text = new_text.TrimEnd(',');
split_text = new_text.Split(',');
MessageBox.Show(split_text.Length.ToString ());
char[] delimiters = new char[] {' ', '\r', '\n' };
whole_text.Split(delimiters,StringSplitOptions.RemoveEmptyEntries).Length;
Since you are only interested in word count, and you don't care about individual words, String.Split could be avoided. String.Split is handy, but it unnecessarily generates a (potentially) large number of String objects, which in turn creates an unnecessary burden on the garbage collector. For each word in your text, a new String object needs to be instantiated, and then soon collected since you are not using it.
For a homework assignment, this may not matter, but if your text box contents change often and you do this calculation inside an event handler, it may be wiser to simply iterate through characters manually. If you really want to use String.Split, then go for a simpler version like Yonix recommended.
Otherwise, use an algorithm similar to this:
int wordCount = 0, index = 0;
// skip whitespace until first word
while (index < text.Length && char.IsWhiteSpace(text[index]))
index++;
while (index < text.Length)
{
// check if current char is part of a word
while (index < text.Length && !char.IsWhiteSpace(text[index]))
index++;
wordCount++;
// skip whitespace until next word
while (index < text.Length && char.IsWhiteSpace(text[index]))
index++;
}
This code should work better with cases where you have multiple spaces between each word, you can test the code online.
There are some better ways to do this, but in keeping with what you've got, try the following:
string whole_text = richTextBox1.Text;
string trimmed_text = whole_text.Trim();
// new line split here
string[] lines = trimmed_text.Split(Environment.NewLine.ToCharArray());
// don't need this here now...
//string[] split_text = trimmed_text.Split(' ');
int space_count = 0;
string new_text = "";
Now make two foreach loops. One for each line and one for counting words within the lines.
foreach (string line in lines)
{
// Modify the inner foreach to do the split on ' ' here
// instead of split_text
foreach (string av in line.Split(' '))
{
if (av == "")
{
space_count++;
}
else
{
new_text = new_text + av + ",";
}
}
}
new_text = new_text.TrimEnd(',');
// use lines here instead of split_text
lines = new_text.Split(',');
MessageBox.Show(lines.Length.ToString());
}
This was a phone screening interview question that I just took (by a large company located in CA who sells all kinds of devices that starts with a letter "i"), and I think I franked... after I got offline, I wrote this. I wish I were able to do it during interview..
static void Main(string[] args)
{
Debug.Assert(CountWords("Hello world") == 2);
Debug.Assert(CountWords(" Hello world") == 2);
Debug.Assert(CountWords("Hello world ") == 2);
Debug.Assert(CountWords("Hello world") == 2);
}
public static int CountWords(string test)
{
int count = 0;
bool wasInWord = false;
bool inWord = false;
for (int i = 0; i < test.Length; i++)
{
if (inWord)
{
wasInWord = true;
}
if (Char.IsWhiteSpace(test[i]))
{
if (wasInWord)
{
count++;
wasInWord = false;
}
inWord = false;
}
else
{
inWord = true;
}
}
// Check to see if we got out with seeing a word
if (wasInWord)
{
count++;
}
return count;
}
Have a look at the Lines property mentioned in #Jay Riggs comment, along with this overload of String.Split to make the code much simpler. Then the simplest approach would be to loop over each line in the Lines property, call String.Split on it, and add the length of the array it returns to a running count.
EDIT: Also, is there any reason you're using a RichTextBox instead of a TextBox with Multiline set to True?
I use an extension method for grabbing word count in a string. Do note, however, that double spaces will mess the count up.
public static int CountWords(this string line)
{
var wordCount = 0;
for (var i = 0; i < line.Length; i++)
if (line[i] == ' ' || i == line.Length - 1)
wordCount++;
return wordCount;
}
}
Your approach is on the right path. I would do something like, passing the text property of richTextBox1 into the method. This however won't be accurate if your rich textbox is formatting HTML, so you'll need to strip out any HTML tags prior to running the word count:
public static int CountWords(string s)
{
int c = 0;
for (int i = 1; i < s.Length; i++)
{
if (char.IsWhiteSpace(s[i - 1]) == true)
{
if (char.IsLetterOrDigit(s[i]) == true ||
char.IsPunctuation(s[i]))
{
c++;
}
}
}
if (s.Length > 2)
{
c++;
}
return c;
}
We used an adapted form of Yoshi's answer, where we fixed the bug where it would not count the last word in a string if there was no white-space after it:
public static int CountWords(string test)
{
int count = 0;
bool inWord = false;
foreach (char t in test)
{
if (char.IsWhiteSpace(t))
{
inWord = false;
}
else
{
if (!inWord) count++;
inWord = true;
}
}
return count;
}
using System.Collections;
using System;
class Program{
public static void Main(string[] args){
//Enter the value of n
int n = Convert.ToInt32(Console.ReadLine());
string[] s = new string[n];
ArrayList arr = new ArrayList();
//enter the elements
for(int i=0;i<n;i++){
s[i] = Console.ReadLine();
}
string str = "";
//Filter out duplicate values and store in arr
foreach(string i in s){
if(str.Contains(i)){
}else{
arr.Add(i);
}
str += i;
}
//Count the string with arr and s variables
foreach(string i in arr){
int count = 0;
foreach(string j in s){
if(i.Equals(j)){
count++;
}
}
Console.WriteLine(i+" - "+count);
}
}
}
int wordCount = 0;
bool previousLetterWasWhiteSpace = false;
foreach (char letter in keyword)
{
if (char.IsWhiteSpace(letter))
{
previousLetterWasWhiteSpace = true;
}
else
{
if (previousLetterWasWhiteSpace)
{
previousLetterWasWhiteSpace = false;
wordCount++;
}
}
}
public static int WordCount(string str)
{
int num=0;
bool wasInaWord=true;;
if (string.IsNullOrEmpty(str))
{
return num;
}
for (int i=0;i< str.Length;i++)
{
if (i!=0)
{
if (str[i]==' ' && str[i-1]!=' ')
{
num++;
wasInaWord=false;
}
}
if (str[i]!=' ')
{
wasInaWord=true;
}
}
if (wasInaWord)
{
num++;
}
return num;
}
class Program
{
static void Main(string[] args)
{
string str;
int i, wrd, l;
StringBuilder sb = new StringBuilder();
Console.Write("\n\nCount the total number of words in a string
:\n");
Console.Write("---------------------------------------------------
---\n");
Console.Write("Input the string : ");
str = Console.ReadLine();
l = 0;
wrd = 1;
foreach (var a in str)
{
sb.Append(a);
if (str[l] == ' ' || str[l] == '\n' || str[l] == '\t')
{
wrd++;
}
l++;
}
Console.WriteLine(sb.Replace(' ', '\n'));
Console.Write("Total number of words in the string is : {0}\n",
wrd);
Console.ReadLine();
}
This should work
input.Split(' ').ToList().Count;
This can show you the number of words in a line
string line = Console.ReadLine();
string[] word = line.Split(' ');
Console.WriteLine("Words " + word.Length);
You can also do it in this way!! Add this method to your extension methods.
public static int WordsCount(this string str)
{
return Regex.Matches(str, #"((\w+(\s?)))").Count;
}
And call it like this.
string someString = "Let me show how I do it!";
int wc = someString.WordsCount();