Display most used vowel in a string c# - 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());

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]++;
}

checking each char in string is outputted in wrong order?

im trying to split a string into a chars(which i have semi done) and use each char to compare it to my dictionary full of random strings, and then add that chars value in the dictionary to a finished string. the problem is what its outputting- the chars are not in order.
ex: USER INPUT: "hello"---
ex: CONSOLE: "e"-"l"-"l"-"o"-"h"
thats what happens mostly. any answer as to how i can get it to spell it correctly in the console?
Code:
private void complete_text_Click(object sender, RoutedEventArgs e)
{
end_result = input_box.Text.ToString();
string end_translated_result = "";
for (int i = 0; i < ZENOX_LANGUAGE.Keys.Count; i ++)
{
foreach (char iq in end_result.ToCharArray())
{
if (iq.ToString().ToLower() == ZENOX_LANGUAGE.Keys.ElementAt(i).ToString().ToLower())
{
Console.WriteLine(iq);
end_translated_result += ZENOX_LANGUAGE.Values.ElementAt(i) + " ";
//Console.WriteLine("sender: " + sender.ToString() + " c: " + end_result[iq].ToString().ToLower() + " s:" + ZENOX_LANGUAGE.Keys.ElementAt(i));
Console.WriteLine("end translated result: " + end_result);
}
}
}
}
As it stands, the order of keys in your dictionary will influence the order that output appears, because you're doing:
foreach(var k in dictionary.Keys)
foreach(char c in someString)
if(c == k)
Console.Write(c)
And dictionary keys have no defined order.
Swapping the loops over will mean (as long as the dictionary has the key you're looking for, as it's a condition that leads to printing the char) that the output will appear in order of chars in the string..
..but I can't actually work out why you enumerate the keys and then run a loop looking for the character. I'd just loop over the string and use the char to index the dictionary if I was building some sort of translator map:
var map = new Dictionary<char, char>() {
{ 'h', 'Z' },
{ 'e', 'Y' },
{ 'l', 'X' },
{ 'o', 'W' }
};
var toTrans = "hello";
foreach(char c in toTrans)
Console.Write(map[c]);
This will print "ZYXXW" for an input of "hello";
If you're mapping chars to strings, with case insensitivity it's as simple as:
var map = new Dictionary<char, string>() {
{ 'h', "Z0" },
{ 'e', "Y0" },
{ 'l', "X0" },
{ 'o', "W0" }
};
var toTrans = "HelLO";
foreach(char c in toTrans)
Console.Write(map[Char.ToLower(c)]);
This will print "Z0Y0X0X0W0"

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);
}

Replacing letters in words

Hello I'm having a little trouble on this one aspect in my code. I have some strings and I have a array of chars. I'm trying to replace the last two letters of each string
with the characters in the char array until the last one.
My array of char is as follows:
char[] array = { 'v', 'x', 'f' };
My code so far:
char[] array = { 'v', 'x', 'f' };
string newWord="";
string apple="apple";
string sam="sam";
foreach(char c in array)
{
apple= apple.Substring(0, apple.Length - 2) +""; ///DON'T KNOW WHAT TO PUT HERE;
sam= sam.Substring(0, sam.Length - 2)+""; ///DON'T KNOW WHAT TO PUT HERE;
newWord = apple+Environment.NewLine+sam ;
}
The output should like like this:
appvx
sfm
Maybe I'm doing this wrong but I'm explicitly telling it in the substring to get rid of the last to letters in the word but if the array runs out won't it still delete the last two. For instance the word sam still needs to have m at the end of it since all the chars in the array have already been used like what the out but shows but replace a with f
something like this?
private static void something()
{
List<char> tokens = new List<char>(new char[]{ 'v', 'x', 'f' });
List<char[]> lArr = new List<char[]>();
lArr.Add("apple".ToCharArray());
lArr.Add("sam".ToCharArray());
List<string> lStr = new List<string>();
int cnt = 2;
foreach (var token in tokens)
{
var aktArr = lArr.FirstOrDefault();
if (aktArr == null)
break;
if (cnt == 0)
{
cnt = 2;
lStr.Add(new string(aktArr));
lArr.RemoveAt(0);
aktArr = lArr.FirstOrDefault();
if (aktArr == null)
break;
}
aktArr[aktArr.Length - cnt--] = token;
}
lStr.AddRange(lArr.Select(x => new string(x)));
foreach (var item in lStr)
{
Console.WriteLine(item);
}
}
You can treat a string as an array of chars, so the result can be something like this (supposing that you have an array of words, not only 2 variables for them and a little helper to replace chars)
var words = new [] {"apple", "sam"};
var wordPos = 0;
for (int i = 0; i < array.Length; i++)
{
var wordLen = words[wordPos].Length;
var letterPos = i % 2 == 0 ? 1 : 2;
words[wordPos] = words[wordPos].ReplaceAt(wordLen - letterPos, letter);
if (letterPos == 1) wordPos++;
}
public static string ReplaceAt(this string input, int index, char newChar)
{
if (input == null)
{
throw new ArgumentNullException("input");
}
char[] chars = input.ToCharArray();
chars[index] = newChar;
return new string(chars);
}
I think something like this will do what you need:
var charArray = new[] {'a', 'b', 'c'};
var words = new List<string> {"apple", "sam"};
var currentWord = 0;
var currentChar = 0;
var charsToReplace = 2;
while (currentChar < charArray.Length && currentWord != words.Count)
{
var word = words[currentWord].ToCharArray();
word[word.Length - charsToReplace] = charArray[currentChar];
words[currentWord] = new string(word);
charsToReplace--;
currentChar++;
if (charsToReplace == 0)
{
charsToReplace = 2;
currentWord++;
}
}
words.ForEach(Console.WriteLine);

How to Count Vowels in a sentence in Text File (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;
}

Categories

Resources