How to Count Vowels in a sentence in Text File (C#) - c#

I have to create a small program where I have to prompt the user for idioms and store these into a text file. After that, I have to open up the text file and count the number of individual vowels in each idiom (a, e, i, o, u) and display these to the user.
Here is the code I have created so far:
int numberOfIdioms;
string fileName = "idioms.txt";
int countA = 0, countE = 0, countI = 0, countO = 0, countU = 0;
Console.Title = "String Functions";
Console.Write("Please enter number of idioms: ");
numberOfIdioms = int.Parse(Console.ReadLine());
string[] idioms = new string[numberOfIdioms];
Console.WriteLine();
for (int aa = 0; aa < idioms.Length; aa++)
{
Console.Write("Enter idiom {0}: ", aa + 1);
idioms[aa] = Console.ReadLine();
}
StreamWriter myIdiomsFile = new StreamWriter(fileName);
for (int a = 0; a < numberOfIdioms; a++)
{
myIdiomsFile.WriteLine("{0}", idioms[a]);
}
myIdiomsFile.Close();

You can use the following code to get the vowel count for a string:
int vowelCount = System.Text.RegularExpressions.Regex.Matches(input, "[aeoiu]").Count;
Replace input with your string variable.
If you want to count regardless of case (upper/lower), you can use:
int vowelCount = System.Text.RegularExpressions.Regex.Matches(input.ToLower(), "[aeoiu]").Count;

string Target = "my name and your name unknown MY NAME AND YOUR NAME UNKNOWN";
List pattern = new List { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
int t = Target.Count(x => pattern.Contains(x));

We can use regular expression to match vowels in each idoms.
you can call the function mentioned below to get the vowel count.
working code snippet:
//below function will return the count of vowels in each idoms(input)
public static int GetVowelCount(string idoms)
{
string pattern = #"[aeiouAEIOU]+"; //regular expression to match vowels
Regex rgx = new Regex(pattern);
return rgx.Matches(idoms).Count;
}

Related

A c# project! should i use String arrays? (is that even a thing?!)

I'm working on a program in c# where I'm supposed to tell the user to insert random characters and then divide those random characters into letters and numbers and count how many i have of each.
anyone has any idea how to do so?
thanks!
ps: i'm new to c# and programming alltogether :)
You could use char.IsDigit or char.IsNumber to check if it's a "number"(digit):
string input = Console.ReadLine();
int digitCount = input.Count(char.IsDigit);
int letterCount = input.Length - digitCount;
You need to add using System.Linq to be able to use Enumerable.Count.
Since you now have asked for counting vowels. Vowels are a, e, i, o, u and their uppercase version. So you could use this method:
private static readonly HashSet<char> Vowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
public static bool IsVowel(char c) => Vowels.Contains(c);
and this code to count the vowels:
int vowelCount = input.Count(IsVowel);
If you don't just want to count them but show them to the user:
string vowelsInInput = new String(input.Where(IsVowel).ToArray());
string noVowels = new String(input.Where(c => !IsVowel(c)).ToArray());
which also gives you the count(for example vowelsInInput.Length).
Get the input and loop through every character within the string
string testStr = "abc123";
foreach (char c in testStr)
{
Console.WriteLine(c.ToString( ));
}
You can use a dictionary to count the number of times a letter appears.
char letter = //your letter;
var charFrequencies = new Dictionary<char, int>();
if (!charFrequencies.ContainsKey(letter)) {
charFrequencies.Add(letter, 1);
}
else {
charFrequencies[letter]++;
}

Count Vowel and Consonant C#

Question
Take input of 1 character from user. It can be the vowel or consonant.
After the user gives input so it will ask do you want to input the character again for Yes press Y and for No press N.
When the user says No, you have to show how much vowel and how much consonant use has input.
Please do this question using For loop. I think array must be use. I did this code it counting vowel and consonant and spacing. But I cant take the input multiple times.
My code doesnn't run multiple times. I can only write sentence or a character in a line so it will only count that. But I want to ask the user to enter a character again.
I want my code to run multiple times so the user can give input multiple times as I explain my question.
using System;
public class vowelConsonant
{
public static void Main()
{
int vowels = 0;
int consonant = 0;
int space = 0;
Console.WriteLine("Enter a Sentence or a Character");
string v = Console.ReadLine().ToLower();
for (int i = 0; i < v.Length; i++)
{
if (v[i] == 'a' || v[i] == 'e' || v[i] == 'i' || v[i] == 'o' || v[i] == 'u')
{
vowels++;
}
else if (char.IsWhiteSpace(v[i]))
{
space++;
}
else
{
consonant++;
}
}
Console.WriteLine("Your total number of vowels is: {0}", vowels);
Console.WriteLine("Your total number of constant is: {0}", consonant);
Console.WriteLine("Your total number of space is: {0}", space);
Console.ReadLine();
}
}
Thanks
Just put an infinite loop around the whole thing.
using System;
public class vowelConsonant
{
public static void Main()
{
// Infinite loop.
while (true)
{
int vowels = 0;
int consonant = 0;
int space = 0;
Console.WriteLine("Enter a Sentence or a Character");
string v = Console.ReadLine().ToLower();
for (int i = 0; i < v.Length; i++)
{
if (v[i] == 'a' || v[i] == 'e' || v[i] == 'i' || v[i] == 'o' || v[i] == 'u')
{
vowels++;
}
else if (char.IsWhiteSpace(v[i]))
{
space++;
}
else
{
consonant++;
}
}
Console.WriteLine("Your total number of vowels is: {0}", vowels);
Console.WriteLine("Your total number of constant is: {0}", consonant);
Console.WriteLine("Your total number of space is: {0}", space);
}
}
}
This application to count vowels and consonants letters in a sentence.
This is another solution with less line of codes with understanding idea of using loop and nested loop with char arrays.
Application interface with controls names
namespace Program8_4
{
public partial class Form1 : Form
{
// declare the counter variables in field
int iNumberOfVowels = 0;
int iNumberOfConsonants = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// call the methods in this event
GetVowels(txtStringInput.Text);
GetConsonants(txtStringInput.Text);
// show the result in a label
lblOutput.Text = "The number of vowels : " + iNumberOfVowels.ToString() + Environment.NewLine+
"The number of consonants : " + iNumberOfConsonants.ToString();
// assign zero the counters to not add the previous number to new number, and start counting from zero again
iNumberOfVowels = 0;
iNumberOfConsonants = 0;
}
private int GetConsonants(string strFindConsonants)
{
// Declare char array to contain consonants letters
char[] chrConsonants = { 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'X',
'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'x' };
// loop to get each letter from sentence
foreach (char Consonants in strFindConsonants)
{
// another nested loop to compare each letter with all letters contains in chrConsonants array
for (int index = 0; index < chrConsonants.Length; index++)
{
// compare each letter with each element in charConsonants array
if (Consonants == chrConsonants[index])
{
// If it is true add one to the counter iNumberOfConsonants
iNumberOfConsonants++;
}
}
}
// return the value of iNumberOfConsonants
return iNumberOfConsonants;
}
private int GetVowels(string strFindVowels)
{
// Declare char array to contain vowels letters
char[] chrVowels = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O','U' };
// loop to get each letter from sentence
foreach (char Vowels in strFindVowels)
{
// another nested loop to compare each letter with all letters contains in chrVowels array
for (int index = 0; index < chrVowels.Length; index++)
{
// compare each letter with each element in chrVowels array
if (Vowels == chrVowels[index])
{
// If it is true add one to the counter iNumberOfVowels
iNumberOfVowels = iNumberOfVowels+1;
}
}
}
// return the value of iNumberOfVowels
return iNumberOfVowels;
}
}
}
We can simply find the required vowels and consonant counts using Regex.Matches() function.
Below is the working code snippet:
public static void Main()
{
Console.WriteLine("Enter a Sentence or a Character");
string input = Console.ReadLine().ToLower();
string vowels = #"[aeiouAEIOU]+"; //regular expression to match vowels
string consonants = #"[^aeiouAEIOU]+"; //regular expression to match consonants
string space = #"[\S]+";
int vowLength = new Regex(vowels).Matches(input).Count;
int conLength = new Regex(consonants).Matches(input).Count;;
int spLength = new Regex(space).Matches(input).Count;;
Console.WriteLine("Your total number of vowels is: {0}", vowLength);
Console.WriteLine("Your total number of constant is: {0}", conLength);
Console.WriteLine("Your total number of space is: {0}", spLength);
}

Display most used vowel in a string c#

I count the vowels and the consonant in a string. Now I want to display the most used vowel and consonant in this string the code that I have for the counting
private void Button_Click(object sender, RoutedEventArgs e)
{
char[] charArray = new char[] { 'a', 'e', 'i', 'o', 'u' };
string line = testBox.Text.ToLower();
char letter;
int vowels = 0;
int sug = 0;
for (int i = 0; i < line.Length; i++)
{
letter = line[i];
if (charArray.Contains(letter))
vowels++;
if (!charArray.Contains(letter))
sug++;
}
MessageBox.Show("number of vowels is" + vowels.ToString());
MessageBox.Show("number of vowels is" + sug.ToString());
}
Make the vowels and constants lists instead of an int counter then you can manipulate each list at a later stage.
private void Button_Click(object sender, RoutedEventArgs e)
{
char[] charArray = new char[] { 'a', 'e', 'i', 'o', 'u' };
string line = testBox.Text.ToLower();
char letter;
List<char> vowels = new List<char>();
List<char> sug = new List<char>();
for (int i = 0; i < line.Length; i++)
{
letter = line[i];
if (charArray.Contains(letter))
vowels.Add(letter);
if (!charArray.Contains(letter))
sug.Add(letter);
}
MessageBox.Show("number of vowels is" + vowels.Count);
MessageBox.Show("number of vowels is" + sug.Count);
MessageBox.Show("most used vowel: " + vowels.GroupBy(x => x).OrderByDescending(xs => xs.Count()).Select(xs => xs.Key).First());
MessageBox.Show("most used constant: " + sug.GroupBy(x => x).OrderByDescending(xs => xs.Count()).Select(xs => xs.Key).First());
}
Ok here is one way to do it. It may be a little more advanced due to the heavy use of linq and lambadas. It does work, but I would recommend breaking some of the functionality out into functions.
char[] charArray = new char[] { 'a', 'e', 'i', 'o', 'u' };
string line = "bbcccaaaeeiiiioouu";
var vowelCounts = new Dictionary<char, int>();
foreach(var vowel in charArray)
{
vowelCounts.Add(vowel, line.Count(charInString => vowel == charInString));
}
var consonantCounts = new Dictionary<char, int>();
foreach(var consonant in line.Where(charInString => !charArray.Contains(charInString)).Distinct())
{
consonantCounts.Add(consonant, line.Count(charInString => consonant == charInString));
}
KeyValuePair<char, int> mostUsedVowel = vowelCounts.OrderBy(Entry => Entry.Value).FirstOrDefault();
KeyValuePair<char, int> mostUsedConsonant = consonantCounts.OrderBy(Entry => Entry.Value).FirstOrDefault();
string output1 = String.Format("The Vowel '{0}' was used {1} times", mostUsedVowel.Key, mostUsedVowel.Value);
string output2 = String.Format("The Consonant '{0}' was used {1} times", mostUsedConsonant.Key, mostUsedConsonant.Value);
MessageBox.Show(output1);
MessageBox.Show(output2);
As String is an enumerable of characters You can use LINQs GroupBy function to group by characters an then do all kinds of evaluation with the groups:
http://dotnetfiddle.net/dmLkVb
var grouped = line.GroupBy(c=> c);
var vowels = grouped.Where(g => charArray.Contains(g.Key));
var mostUsed = vowels.OrderBy(v => v.Count()).Last();
Console.WriteLine("Distinct characters: {0}:", grouped.Count());
Console.WriteLine("Vowels: {0}:", vowels.Count());
Console.WriteLine("Most used vowel: {0} - {1}:", mostUsed.Key, mostUsed.Count());

Count vowels, consonsants, digits, and other char in a entered string of text (language c#)

Can someone please look at my code? I need to count the characters from the entered textbox and have them display in the correct label box. (consonant, vowel, digit and other) I did have the digit one working and them messed it up working on the vowels.
// determines if the text is a consonant, vowel, digit or other character. Then it displays the count of each.
int consCount = 0;
int vowelCount = 0;
int digitCount = 0;
int otherCount = 0;
string inputString;
inputString = this.entryTextBox.Text.ToLower();
char[] vowels = new char[] {'a', 'e', 'i', 'o', 'u'};
string vow = new string(vowels);
for (int index = 0; index < inputString.Length; index++)
{
if (char.IsLetterOrDigit(inputString[index]))
{
if (inputString.Contains(vow))
vowelCount++;
}
else if (char.IsDigit(inputString[index]))
digitCount++;
}
this.voweldisplayLabel.Text = vowelCount.ToString();
this.digitsdisplayLabel.Text = digitCount.ToString();
this.constdisplayLabel.Text = consCount.ToString();
this.otherdisplayLabel.Text = otherCount.ToString();
There are two problems in the code you posted:
The placement of the else lines up with the for and not the if, as it should.
String.Contains is trying to match up the entire char set...it is not picking it apart and looking for every character individually (it will only be true when the string contains aeiou as a chunk). You could use Linq to accomplish this as a one-liner if you'd like. Otherwise, nest a foreach and loop across the char list to find your match.
I think you messed up with the else statement. It should be directly after the closing bracket of the if statement. But here it's behind the closing bracket of the for loop. Maybe you need some sleep ;)
I figured it out. I got both the vowels and digits to display properly. =) Now I am off to work on the consonants and other characters.
int vowelCount = 0;
int digitCount = 0;
string inputString;
inputString = this.entryTextBox.Text.ToLower();
char[] vowels = new char[] { 'a', 'e', 'i', 'o', 'u' };
string vow = new string(vowels);
for (int index = 0; index < inputString.Length; index++)
{
if (char.IsLetterOrDigit(inputString[index]))
{
if (vow.Contains(inputString[index]))
{
vowelCount++;
}
else if (char.IsDigit(inputString[index]))
digitCount++;
}
}
this.voweldisplayLabel.Text = vowelCount.ToString();
this.digitsdisplayLabel.Text = digitCount.ToString();

Use more than one character to replace other

I have a app and in this app it is possible with a function to replace some characters in a word with a other character
var newCharacter = "H";
if (/*something happens here and than the currentCharacter will be replaced*/)
{
// Replace the currentCharacter in the word with a random newCharacter.
wordString = wordString.Replace(currentCharacter, newCharacter);
}
now all the characters will be replaced with the code above with the "H". But i want more letters so by example the H, E, A, S
what is the best way to do this?
When i do this:
var newCharacter = "H" + "L" + "S";
it replaced the currentCharacter with H AND L AND S but i just want it to replace with H OR L OR S not all three
so if you have a word with HELLO and you want to replace the O with the newCharacter my output now is HELLHLS
O -> HLS
but O needs to be -> H or L or S
Here is a way to do using LINQ.You can add the characters you want to remove in the array excpChar
char[] excpChar= new[] { 'O','N' };
string word = "LONDON";
var result = excpChar.Select(ch => word = word.Replace(ch.ToString(), ""));
Console.WriteLine(result.Last());
The Replace function replaces all the occurences at once, this is not what we want. Let's do a ReplaceFirst function, only replacing the first occurence (one could make an extension method out of this):
static string ReplaceFirst(string word, char find, char replacement)
{
int location = word.IndexOf(find);
if (location > -1)
return word.Substring(0, location) + replacement + word.Substring(location + 1);
else
return word;
}
Then we can use a random generator to replace the target letter with different letters through successive calls of ReplaceFirst:
string word = "TpqsdfTsqfdTomTmeT";
char find = 'T';
char[] replacements = { 'H', 'E', 'A', 'S' };
Random random = new Random();
while (word.Contains(find))
word = ReplaceFirst(word, find, replacements[random.Next(replacements.Length)]);
word now may be EpqsdfSsqfdEomHmeS or SpqsdfSsqfdHomHmeE or ...
You can do like following :
string test = "abcde";
var result = ChangeFor(test, new char[] {'b', 'c'}, 'z');
// result = "azzde"
with ChangeFor :
private string ChangeFor(string input, IEnumerable<char> before, char after)
{
string result = input;
foreach (char c in before)
{
result = result.Replace(c, after);
}
return result;
}

Categories

Resources