1) I need to count how much words i have in the sentence.
But what if i have more than one white space? It will count as a word. Need solution for this.
There is four words. / count as 4 words
There is four words. / count as 5 words
I use:
int countWords = txt.Split().Length;
2) I need to extract numbers from string and then get sum. My code is not working, No overload for method error.
All my code:
Console.Write("Ievadiet tekstu: ");
string txt = Console.ReadLine();
int sum = 0;
int countWords = txt.Split().Length;
foreach (char num in txt)
{
if (char.IsDigit(num))
sum += Int32.TryParse(num).ToString();
}
Console.WriteLine("There are {0} words in this sentence.",countWords);
Console.WriteLine("Summ is "+sum);
Use the overload of String.Split with StringSplitOptions.RemoveEmptyEntries. You can use an empty char[](or string[]) to get the same behaviour as String.Split without an argument, so that it splits by all white-space characters like space,tab or new-line characters.
If you want to sum the "words" which could be parsed to int then do that, use int.TryParse on all words which were extracted by String.Split. You could use LINQ:
string[] words = text.Split(new char[] {}, StringSplitOptions.RemoveEmptyEntries);
int wordCount = words.Length;
int num = 0;
int sum = words.Where(w => int.TryParse(w, out num)).Sum(w => num);
Here is a simple console app to do what you intend to.
It uses a Regular expression to capture number characters and sums them. The TryParse is just a fail-safe (i believe it is not needed in this case since the regex ensures only digits are captured).
static void Main(string[] args)
{
Regex digitRegex = new Regex("(\\d)");
string text = Console.ReadLine();
int wordCount = text.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries).Length;
int sum = 0;
foreach (Match x in digitRegex.Matches(text, 0))
{
int num;
if (int.TryParse(x.Value, out num))
sum += num;
}
Console.WriteLine("Word Count:{0}, Digits Total:{1}", wordCount, sum);
Console.ReadLine();
}
Hope it helps. Cheers
Related
How can I make it so that text.Split(' ')[0] increments? I would like it to do text.Split(' ')[++] but putting that ++ in there doesn't work. The goal is to have the code count the "search" words. Sorry, new to c#.
using System;
namespace TESTER
{
class Program
{
static void Main(string[] args)
{
int wordCount = 0;
int index = 0;
string text = "I ate a donut on national donut day and it tasted like a donut";
string search = "donut";
// skip whitespace until first word
while (index < text.Length)
{
if (search == text.Split(' ')[0])
{
wordCount++;
}
}
Console.WriteLine(wordCount);
}
}
}
You could just do this:
string text = "I ate a donut on national donut day and it tasted like a donut";
string search = "donut";
int wordCount = text.Split(' ').Count(x => x == search);
Console.WriteLine(wordCount);
That gives 3.
Try doing this.
using System;
namespace TESTER
{
class Program
{
static void Main(string[] args)
{
int wordCount = 0;
int index = 0;
string text = "I ate a donut on national donut day and it tasted like a donut";
string search = "donut";
// skip whitespace until first word
string[] wordArray = text.Split(' ');
while (index < wordArray.Length)
{
if (search == wordArray[index])
{
wordCount++;
}
index++;
}
Console.WriteLine(wordCount);
}
}
}
You can use this:
using System;
using System.Linq;
namespace TESTER
{
class Program
{
static void Main(string[] args)
{
string text = "I ate a donut on national donut day and it tasted like a donut";
string search = "donut";
var wordCount = text.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Count(x => x == search);
Console.WriteLine(wordCount);
}
}
}
If you want a case-insensitive search use:
var wordCount = text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Count(
x => string.Equals(x, search, StringComparison.InvariantCultureIgnoreCase)
);
The answer of Enigmativity is the right one. That's how you should do what you want.
But you're learning and using LINQ won't make it easier.
Your variable text is of string. When you use the member function Split(...) of the type string (or String, which is the same), it will return an array of string. This is string[]. To use the [] you can declare such an object.
string[] words;
Then you assign the result of your text.Split(' ') to it.
words = text.Split(' ');
This gives you access to all entries through the variable words.
string str = words[0];
To count without LINQ you can iterate through the array. Think this was you intention with the [++]. You have two options.
Use a for-loop or a foreach.
int wordCount = 0;
for( int i = 0; i < words.Count )
{
if( words[i] == search)
++wordCount;
}
or the foreach-loop
// let pretend it's a real program here and
// reset the wordCount rather then declaring it
wordCount = 0;
foreach( string str in words )
{
if( words[i] == search)
++wordCount;
}
Incrementation with the ++ sign, or it's opposite --:
These need a number. For instance an int.
int number = 0;
This you can increment with:
number++;
Now number will have the value of 1.
You can use it in the indexer of an array. But you do need an integer.
Consider this code:
int index = 0;
while(index < words.Length)
{
Console.WriteLine( words[ index++ ] );
}
Here you have the array words. In the indexer you request entry of what number holds as value. Then index will be incremented by 1 and due to the while-loop index will be 14 upon exiting the while-loop. 14 is the number of words in your initial string.
I need an idea.
This is what I tried:
string text = Console.ReadLine();
int number = Convert.ToInt32(Console.ReadLine());
char[] mychar = { ' ' };
int n = 0;
string[] wordslist = text.Split(mychar);
foreach (char in text)
n = n+1;
if (n+1<number)
Console.WriteLine("N/A");
else
Console.WriteLine(wordslist[number-1]);
If the number inputted is bigger than the number of words from string it should return "N/A".
It works if I don't use the foreach loop for number lower or equal with the words number.
var text = Console.ReadLine();
int number;
while(!int.TryParse(Console.ReadLine(), out number);
var words = text.Split(' ');
if(words.Count > number)
{
Console.WriteLine(words[number]);
}
else
{
Console.WriteLine("N/A");
}
This sounds like homework...
I have a multiline textbox that contains 10 digit mobile numbers separated by comma. I need to achieve string in group of at least 100 mobile numbers.
100 mobile numbers will be separated by 99 comma in total. What i am trying to code is to split the strings containing commas less than 100
public static IEnumerable<string> SplitByLength(this string str, int maxLength)
{
for (int index = 0; index < str.Length; index += maxLength) {
yield return str.Substring(index, Math.Min(maxLength, str.Length - index));
}
}
By using above code, I can achieve 100 numbers as 100 numbers will have 10*100(for mobile number)+99(for comma) text length. But the problem here is user may enter wrong mobile number like 9 digits or even 11 digits.
Can anyone guide me on how can I achieve this.
Thank you in advance.
You could use this extension method to put them into max-100 number groups:
public static IEnumerable<string[]> SplitByLength(this string str, string[] splitBy, StringSplitOptions options, int maxLength = int.MaxValue)
{
var allTokens = str.Split(splitBy, options);
for (int index = 0; index < allTokens.Length; index += maxLength)
{
int length = Math.Min(maxLength, allTokens.Length - index);
string[] part = new string[length];
Array.Copy(allTokens, index, part, 0, length);
yield return part;
}
}
Sample:
string text = string.Join(",", Enumerable.Range(0, 1111).Select(i => "123456789"));
var phoneNumbersIn100Groups = text.SplitByLength(new[] { "," }, StringSplitOptions.None, 100);
foreach (string[] part in phoneNumbersIn100Groups)
{
Assert.IsTrue(part.Length <= 100);
Console.WriteLine(String.Join("|", part));
}
You have a few options,
Put some kind of mask on the input data to prevent the user entering invalid data. In your UI you could then flag the error and prompt the user to reenter correct information. If you go down this route then something like this string[] nums = numbers.Split(','); will be fine.
Alternatively, you could use regex.split or regex.match and match on the pattern. Something like this should work assuming your numbers are in a string with a leading comma or space
Regex regex = new Regex("(\s|,)\d{10},)";
string[] nums = regex.Split(numbers);
This be can resolved with a simple Linq code
public static IEnumerable<string> SplitByLength(this string input, int groupSize)
{
// First split the input to the comma.
// this will give us an array of all single numbers
string[] numbers = input.Split(',');
// Now loop over this array in groupSize blocks
for (int index = 0; index < numbers.Length; index+=groupSize)
{
// Skip numbers from the starting position and
// take the following groupSize numbers,
// join them in a string comma separated and return
yield return string.Join(",", numbers.Skip(index).Take(groupSize));
}
}
This program counts and displays the number of words and the number of characters as the user is typing. The "word counter" is working fine, but I cannot figure out how to count the characters without counting the spaces in between.
private void userTextBox_TextChanged(object sender, EventArgs e)
{
string userInput = userTextBox.Text;
userInput = userInput.Trim();
string[] wordCount = userInput.Split(null);
//Here is my error
string[] charCount = wordCount.Length;
wordCountOutput.Text = wordCount.Length.ToString();
charCountOutput.Text = charCount.Length.ToString();
}
Since you're name is "Learning2Code" I thought I'd give you an answer that fixes your original attempt using the least advanced technique:
private void userTextBox_TextChanged(object sender, EventArgs e)
{
string userInput = userTextBox.Text;
userInput = userInput.Trim();
string[] wordCount = userInput.Split(null);
int charCount = 0;
foreach (var word in wordCount)
charCount += word.Length;
wordCountOutput.Text = wordCount.Length.ToString();
charCountOutput.Text = charCount.ToString();
}
You could use LINQ to count characters without white-spaces:
int charCount = userInput.Count(c => !Char.IsWhiteSpace(c));
However, your code suggests that you just don't know how to count the words, so
replace
string[] charCount = wordCount.Length;
with
int words = wordCount.Length;
You have each word already, so count the characters in each word and sum the total:
var charCount = words.Sum(w => w.Length);
Note: you stored the word array as 'wordCount' - I renamed it to just 'words' in the above snippet to be semantically correct. ie:
string[] words = userInput.Split(null);
Just replace all the spaces (and new lines characters) with Regex:
Regex.Replace(inputString, "[\s\n]", "");
There is one space less than the number of words (for example "once upon a time" contains four words and three spaces), so you can calculate the number of spaces. Then just subtract the number of spaces from the length of the input string:
int charCount = userInput.Length - (wordCount.Length - 1);
As that is an integer and not a string array, don't use Length when you output the result:
charCountOutput.Text = charCount.ToString();
I'm stuck on how to count how many words are in each sentence, an example of this is: string sentence = "hello how are you. I am good. that's good."
and have it come out like:
//sentence1: 4 words
//sentence2: 3 words
//sentence3: 2 words
I can get the number of sentences
public int GetNoOfWords(string s)
{
return s.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
label2.Text = (GetNoOfWords(sentance).ToString());
and i can get the number of words in the whole string
public int CountWord (string text)
{
int count = 0;
for (int i = 0; i < text.Length; i++)
{
if (text[i] != ' ')
{
if ((i + 1) == text.Length)
{
count++;
}
else
{
if(text[i + 1] == ' ')
{
count++;
}
}
}
}
return count;
}
then button1
int words = CountWord(sentance);
label4.Text = (words.ToString());
But I can't count how many words are in each sentence.
Instead of looping over the string as you do in CountWords I would just use;
int words = s.Split(' ').Length;
It's much more clean and simple. You split on white spaces which returns an array of all the words, the length of that array is the number of words in the string.
Why not use Split instead?
var sentences = "hello how are you. I am good. that's good.";
foreach (var sentence in sentences.TrimEnd('.').Split('.'))
Console.WriteLine(sentence.Trim().Split(' ').Count());
If you want number of words in each sentence, you need to
string s = "This is a sentence. Also this counts. This one is also a thing.";
string[] sentences = s.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
foreach(string sentence in sentences)
{
Console.WriteLine(sentence.Split(' ').Length + " words in sentence *" + sentence + "*");
}
Use CountWord on each element of the array returned by s.Split:
string sentence = "hello how are you. I am good. that's good.";
string[] words = sentence.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).Length;
for (string sentence in sentences)
{
int noOfWordsInSentence = CountWord(sentence);
}
string text = "hello how are you. I am good. that's good.";
string[] sentences = s.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
IEnumerable<int> wordsPerSentence = sentences.Select(s => s.Trim().Split(' ').Length);
As noted in several answers here, look at String functions like Split, Trim, Replace, etc to get you going. All answers here will solve your simple example, but here are some sentences which they may fail to analyse correctly;
"Hello, how are you?" (no '.' to parse on)
"That apple costs $1.50." (a '.' used as a decimal)
"I like whitespace . "
"Word"
If you only need a count, I'd avoid Split() -- it takes up unnecessary space. Perhaps:
static int WordCount(string s)
{
int wordCount = 0;
for(int i = 0; i < s.Length - 1; i++)
if (Char.IsWhiteSpace(s[i]) && !Char.IsWhiteSpace(s[i + 1]) && i > 0)
wordCount++;
return ++wordCount;
}
public static void Main()
{
Console.WriteLine(WordCount(" H elloWor ld g ")); // prints "4"
}
It counts based on the number of spaces (1 space = 2 words). Consecutive spaces are ignored.
Does your spelling of sentence in:
int words = CountWord(sentance);
have anything to do with it?