How to determine if string ends in vowel or consonant? - c#

hello my teacher gave me a task to create a program to :
(1) find how many vowels are there in a string
(2) and determine if a string ends in a vowel or consonant
I did the first requirement but I had no idea about the second one. since I'm still a beginner in this field. can anyone help me? what should I do with the second requirement?
and the result should be like this :
Enter a string: stack; Ends in consonant; Total Vowels: 1

Linq approach
char[] vocals = "aeiouAEIOU".ToCharArray();
string input = "testo";
int vocalCount = input.Count(vocals.Contains);
bool endsWithVocal = vocals.Any(input.Last().Equals);

Welcome to stackoverflow Blue Azzure,
there are many ways to get this second task done. One approach could be
Get the last character as char (char ch = lc[lc.Length - 1];)
Make the text lowercase (var lc = ch.ToLowerInvariant())
Evaluating the character type:
checking agains the vowels (e.g. ch == 'a'): if true -> it is a vowel
checking the ASCII-value of the character is inside the lowercase letters range (c >= 97 && c <= 122): if true -> it is a consonant
otherwise the last character is neither vowel nor consonant

You can split your string into char array then use array[length-1] to access last character and check it through for loop if it contains 'a,e,i,o,u'.
If it does it is vowel otherwise not :)

Related

Checking syntax of strings - C#

I'm trying to find out how to analyze the syntax of a sentence in C#.
In my case I have a syntax which every sentence has to follow.
The syntax looks like this:
A 'B' is a 'C'.
Every sentence has to contain five words. The first word of my sentence has to be 'A', the third 'is' and the fourth 'a'.
Now I would like to examine a test sentence if it matches my syntax.
Test sentence:
A Dog is no Cat.
In this example the test sentence would be wrong, because the fourth word is 'no' and not 'a' what it should be basend on the syntax.
I read about LINQ where I can query sentences that contain a specified set of words.
The code would look something like this:
//Notice the third sentence would have the correct syntax
string text = "A Dog is no Cat. My Dog is a Cat. A Dog is a Cat.";
//Splitting text into single sentences
string[] sentences = text.Split(new char[] { '.'});
//Defining the search terms
string[] wordToMatch ={"A", "is"};
//Find sentences that contain all terms I'm looking for
var sentenceQuery = from sentence in sentences
let w = sentence.Split(new Char[] {'.'})
where w.Distinct().Intersect(wordsToMatch).Count == wordsToMatch.Count()
select sentence;
With this code I could check if the sentences contain my terms I'm looking for, but the problem is it's not checking the position of the words in the sentence.
Is there a way I could check the position as well or maybe a better way to check the syntax of a sentence with C#?
Try using regular expressions, something like this:
using System.Text.RegularExpressions;
...
string source = "A Dog is no Cat.";
bool result = Regex.IsMatch(source, #"^A\s+[A-Za-z0-9]+\s+is\s+a\s+[A-Za-z0-9]+\.$");
Pattern explanation:
^ - start of the string (anchor)
A - Letter A
\s+ - one or more whitelines (spaces)
[A-Za-z0-9]+ - 1st word (can contain A..Z, a..z letters and 0..9 digits)
\s+ - one or more whitelines (spaces)
is - is
\s+ - one or more whitelines (spaces)
a - a
\s+ - one or more whitelines (spaces)
[A-Za-z0-9]+ - 2nd word (can contain A..Z, a..z letters and 0..9 digits)
\. - full stop
$ - end of the string (anchor)
You can slightly modify the code and obtain actual 1st and 2nd strings' values:
string source = "A Dog is a Cat."; // valid string
string pattern =
#"^A\s+(?<First>[A-Za-z0-9]+)\s+is\s+a\s+(?<Second>[A-Za-z0-9]+)\.$";
var match = Regex.Match(source, pattern);
if (match.Success) {
string first = match.Groups["First"].Value; // "Dog"
string second = match.Groups["Second"].Value; // "Cat"
...
}
A regular expression would work for this, and would be the most concise, but may not be the most readable solution. Here is a simple method that will return true if the sentence is valid:
private bool IsSentenceValid(string sentence)
{
// split the sentence into an array of words
char[] splitOn = new char[] {' '};
string[] words = sentence.ToLower().Split(splitOn); // make all chars lowercase for easy comparison
// check for 5 words.
if (words.Length != 5)
return false;
// check for required words
if (words[0] != "a" || words[2] != "is" || words[3] != "a")
return false;
// if we got here, we're fine!
return true;
}
Just want to throw ideas. I would write three classes for this:
SentenceManager: which gets string as a sentence and has a public method public string GetWord(word_index). for example GetWord(3) would return the 3rd word in the sentence that has been given to the class constructor.
SentenceSyntax: in this class, you can say how many words your sentence must have. what words must be known and you can set the index of those words too.
SyntaxChecker: this class gets a SentenceSyntax object and a SentenceManager object and has a function called Check which returns true if the syntax matches the sentence.
remember there can be thousands of ways to make something work. but there are some few ways to do it right.
You should definitely do this using Regex or something similar like Dmitry has answered
Just for kicks, I wanted to do it your way. This is how I would do if I was going nuts :)
//Notice the third sentence would have the correct syntax
string text = "A Dog is no Cat.My Dog is a Cat.A Dog is a Cat.";
//Splitting text into single sentences
string[] sentences = text.Split(new char[] { '.' });
string[] wordsToMatch = { "A", "*", "is", "a", "*" };
var sentenceQuery = from sentence in sentences
let words = sentence.Split(' ')
where words.Length == wordsToMatch.Length &&
wordsToMatch.Zip(words, (f, s) => f == "*" || f == s).All(p => p)
select sentence;
Using this code, you can also get flexibility like cases insensitive comparison, and trim space around the word, etc - of course you will have to code for that

Perform Select at odd positions in the string

I have to Replace the characters of input string at odd positions by next character in alphabet.
For Example
Input- ABCD
output- BBDD
I wanted something like this
string input = Console.ReadLine();
char[] k = input.ToCharArray().Select((val,i) =>(i%2==0) && (char)((int)val + 1)).ToArray();
string output=new string(k)
You are almost there, need to do little more to achieve the target. You have to notice the Following things and make those changes:
The condition i%2==0 determines whether the character needs to be replaced or not, so you have to apply the conditional operator(?:) here.
For valid condition, you have to get the next character. For that you can try (char)((int)x + 1). this will first evaluate (int)x and gives the integer value of that particular character. then add 1 to it then get the corresponding character.
For false condition use the same character.
After these steps you will get a character array, you can use String.Join to make the output string from the character array
You can try something like this:
string input = "ABCD";
char[] k = input.Select((x, i) => i % 2 == 0 ? (char)((int)x + 1) : x).ToArray();
string output = String.Join("",k);
Working Example
Note the following things as well:
In this code we have not restricted characters, if your input contains Z the next value from the ASCII table will be assigned, that will be [.
If you want z to a and Z to A then you have to apply conditions for that.
string output = string.Concat(input.Select((c, i) => (char)(c + ++i % 2)));

Determine if string is made up of characters from a different string (Scrabble-like program)

I am writing a program in C# that goes through a list of words and determines if they can be made up by a string that a user input. Just like the Scrabble game.
For example, when the user inputs the string "vacation", my program is supposed to go through a list of words that I already have and should return true when it gets to words like "cat". So it doesn't necessarily have to user ALL the letters.
Another example could be the word "overflow", it should return true with words like "over", "flow", "low", "lover". If the input word has repeating characters by N times, the word that matches can also have that letter up to N times but no more.
I currently have something like this:
var desiredChars = "ent";
var word = "element";
bool contains = desiredChars.All(word.Contains);
However, this checks if it contains all of the letters. I want to check if it contains ONLY those letters or less but ONLY those that can be made up with letters that the user passed.
If it wasn't for the issue of possible multiple letters (for "overflow", the word "fool" is a match, but "wow" isn't, because there aren't two w characters in the letter set), this Linq code would work
string letters = "overflow";
string word = "lover";
bool match = !word.Except(letters).Any(); // unfortunately, not sufficient
So, to handle the multiple letter issue, something like this is needed:
var letterChars = letters.ToList();
bool match = word.All(i => letterChars.Remove(i));
Here, we return true only if all the letters in the word can successfully be removed from the set of letters. Note that you only need to check those words in your dictionary that start with one of the letters in your letter set.
That worked for your example:
public static bool IsWordPartOfString(string startString, string word)
{
var tempTable = startString.ToArray();
foreach (var c in word)
{
var index = Array.FindIndex(tempTable, myChar => myChar == c);
if (index == -1)
{
return false;
}
tempTable[index] = ' ';
}
return true;
}
Steps:
1) Convert startString into an array
2) Iterate chars of the tested word
3) If char not found in startString return false
4) If char found in startString find it in the tempTable and remove so it
cannot be reused (to prevent scenario when startString has only one occurrence of a letter but the test word has multiple)
5) If possible to iterate through the whole word it means it all can be constructed from the letters in initial string so return true.

Pig Latin Console

Hi I'm doing Pig Latin for class, the instructions were first consonant is removed from the front of the word, and put on the back of the word. Then followed by the letters "ay." examples are, book becomes ookbay, and strength becomes engthstray. I'm having trouble because it doesn't do the first consonant.
// button, three, nix, eagle, and troubadour
Console.Write("Enter word you want in Pig Latin: ");
string word1 = Console.ReadLine();
string pig = "";
string vowels = "aeiouAEIOU";
string space = " ";
string extra = ""; //extra letters
int pos = 0; //position
foreach (string word in word1.Split())
{
if (pos != 0)
{
pig = pig + space;
}
else
{
pos = 1;
}
vowels = word.Substring(0,1);
extra = word.Substring(1, word.Length - 1);
pig = pig + extra + vowels + "ay";
}
Console.WriteLine(pig.ToString());
For example if I do strength it will come up as trengthsay and not like the example
You've got a number of problems there. First of all, your definition of the problem:
the instructions were first consonant is removed from the front of the word
That is precisely what you have done. strength does become trengths if you move the first consonant. You need to change your definition to all leading consonants up to the first vowel. Also, what do you do in the case of eagle? Does it become eagleay? Your instructions don't specify how to deal with a leading vowel.
This is another problem
vowels = word.Substring(0,1); // This will overwrite your vowel array with the first letter
Don't worry about writing real code just yet, write some pseudo-code to work out your logic first. #Chris's comment about looking for the first vowel is a good one. Your pseudo code may look something like:
Check if word begins with consonant
{
If so, look for index of first vowel
Take substring of word up to first vowel.
Append it to end
}
Otherwise
{
Deal with leading vowel
}

Algorithm to extract 2 levels down

Hi guys i have the following string
&|L1|L2|L3|&
I would like to extract L1 out and do some if statement to it. Meaning i would have to read for each & & and | | then extract L1?
THanks for your help!
                                          
THe string is not fixed >.< sometimes its
&|L1|A2|A3|& %3123%                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
If you know your data is always formatted like this, and you always want the substring contained between the first and second pipe characters, a simple regex will work (this is in C#, as that's what you've tagged the question with):
string testString = "&|L1|L2|L3|&";
string match = Regex.Match(testString, #"^.+?\|(.+?)\|").Groups[1].Value;
You can then perform whatever logic you need to on "match". Regex explanation: match the start of the string followed by a lazy match of any characters up to the first pipe, lazy match and capture any characters up to the next pipe.
You can check by looping the each char or all the chars at a time. See the below code
string Str = "&|L1|L2|L3|&";
for(int i= 0;i<Str.Length;i++)
{
if (Str[i] == 'L' && Str[i+1] == '1')
{
MessageBox.Show(Str[i].ToString() + Str[i+1].ToString() + " Found");
}
}

Categories