How do I do this with basic string functions and loop? I want to count the words in a string. My problem is that it only works when the user do not use multiple spaces.
Here is my code:
string phrase;
int word = 1;
Console.Write("Enter a phrase: ");
phrase = Console.ReadLine();
for (int i = 0; i<phrase.Length; i )
{
if (name[i] == ' ')
{
word ;
}
}
Console.WriteLine(word);
CodePudding user response:
One approach is to use a regular expression to "condense" all consecutive spaces into a single instance. Then the job is simple.
var str = "aaa bb cccc d e";
var regex = new Regex(@"\s ");
Console.WriteLine(regex.Replace(str, " ")?.Split(' ')?.Count());
CodePudding user response:
If you can use LINQ, i suggest this approach:
string[] source = phrase.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries);
var matchQuery = from word in source
select word;
int wordCount = matchQuery.Count();
Console.WriteLine(wordCount);
CodePudding user response:
I would create an array with string data type. Then I would use Split method when reading the data. This would split the entire text anytime you see a defined character (character is a one letter or character). In your case the defined character would be empty space; that is ' '. So my formula would be something like:
string phrase;
string[] seperated; // this is where you would split the full name
int word = 1;
Console.Write("Enter a phrase: ");
phrase = Console.ReadLine();
seperated=phrase.Split(' ');
for (int i = 0; i<seperated.Length; i )
{
Console.WriteLine(seperated[i]); // this would print each word one by one
}
Once capture the full name split in seperated array, than you can use the seperated name, last name etc the way you want. seperated[0]= would be the first word, seperated[1] would be the second word... if the name consists of total 5 words than the last word could be reached by seperated[4].
CodePudding user response:
Instead of the for loop you could use Split() and Linq:
var splitPhrase = phrase.Split(' ');
var wordCount = splitPhrase.Count(x=>x != "");
or use StringSplitOptions, as per comment:
var words = phrase.Split(' ', StringSplitOptions.RemoveEmptyEntrie);
var wordCount = words.Count();
CodePudding user response:
You can use regex pattern: \S matches anything but a whitespace
string str = "Test words test"
MatchCollection collection = Regex.Matches(str, @"[\S] ");
int numberOfWords = collection.Count;
CodePudding user response:
First of all, we have to define word. If word is
Any non empty sequence of letters
we can use a simple regular expression pattern: \p{L}
Code:
using System.Text.RegularExpressions;
...
int word = Regex.Matches(phrase, @"\p{L} ").Count;
Edit: in case you don't want regular expressions you can implement FSM - Finite State Machine:
int word = 0;
bool inWord = false;
foreach (var c in phrase)
if (char.IsLetter(c)) {
if (!inWord) // we count beginnings of each word
word = 1;
inWord = true;
}
else
inWord = false;
Here we have two states: - inWord == true, false
- which are if character is within some word or not. Having these states we can count all the words beginnings.
CodePudding user response:
You can achieve this by using the following function.It only returns the no. of words in the given sentence.
public int totalWords(string sentence) {
int wordCount = 0;
for (int i = 0; i < sentence.Length - 1; i )
{
if (sentence[i] == ' ' && Char.IsLetter(sentence[i 1]) && (i > 0))
{
wordCount ;
}
}
wordCount ;
return wordCount;
}
CodePudding user response:
Assuming your words are separated by a space you can just Split
the string and get the length of the resulting array:
string[] words = phrase.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
int numberOfWords = words.Length;