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
}
Related
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 :)
This program checks every character in a sentence. Every time the character is a space(" ") the numberOfWords (variable) will be incremented by 1.
Is this the right way to do it?
string sentence;
int numberOfWords;
int sentenceLength;
int counter;
string letter;
Console.Write("Sentence :");
sentence = Console.ReadLine();
sentenceLength = sentence.Length;
numberOfWords = 1;
counter = 0;
while (counter < sentenceLength)
{
letter = Convert.ToString(sentence[counter]);
if (letter == " ")
{
numberOfWords++;
counter++;
}
else
{
counter++;
}
}
Console.Write("Number of words in this sentence :");
Console.WriteLine(numberOfWords);
Console.ReadLine();
Well, the easy answer is; don't reinvent the wheel, use existing tools:
var numberOfWords =
sentence.Split(
' ',
StringSplitOptions.
RemoveEmptyEntries).Length;
But that would be cheating...
So, taking your code, there are a few things that need to be fixed:
First, don't make your method do too many things. There is no reason why a method counting words should know anything about how to output the result to any given user interface. Simply make a method that knows how to count words and returns the number of words:
public static int CountWords(string sentence) { ...}
Now you can reuse this method in any type of application; console, windows forms, WPF, etc.
Second, take corner or trivial cases out of the equation fast. Null sentences are either an error or have no words. Make a choice on how you want to process this scenario. If 0 words makes sense, you can solve a few cases in one strike:
if (string.IsNullOrWhiteSpace(sentence))
return 0;
Third, don't perform unnecessary conversions; converting chars to strings simply to perform an equality check with " " is wasteful. Compare chars directly (' '), or use the aptly named char.IsWhiteSpace(+) method.
Fourth, your logic is flawed. Double spaces, leading spaces, etc. will all give you wrong results. The reason being that your condition on when to count a word is faulty. Encountering a whitespace doesn't necessarily mean a new word is on the way; another whitespace might be waiting, you’ve already encountered a white space in the previous iteration, the sentence might end, etc.
In order to make your logic work you need to keep track of what happened before, what’s happening now and what will happen next... if that sounds messy and over complicated, don’t worry, you are absolutely right.
A simpler way is to shift your logic just a little; let’s say we encounter a new word everytime we find a non whitespace(*) that is preceded by a whitespace. What happens after is irrelevant, so we’ve just made things a lot easier:
var counter = 0;
var words = 0;,
var previousIsWhiteSpace = false;
while (counter < sentence.Length)
{
if (char.IsWhiteSpace(sentence[counter]))
{
previousIsWhiteSpace = true;
}
else if (previousIsWhiteSpace)
{
words += 1;
previousIsWhiteSpace = false;
}
counter += 1;
}
Put it all together and you are done.
(+) this will actually flag more than a regular space as a valid whitespace; tab, new line, etc. will all return true.
(*) I’m ignoring scenarios involving punctuation marks, separators, etc.
Just sticking with the style of your implementation, assuming the input is only split by single spaces, it's much nicer to just split your sentence string on each white space character.
string[] words = sentence.Trim().Split(null);
using null as the argument, white space will be used to split. Trim() removes trailing and leading space characters.
Then, using words.Length you can easily get how many words there are separated by white space. However, this won't account for double spaces or empty sentences. Removing double or more spaces is best achieved with regex.
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
sentence = regex.Replace(sentence, " ");
I've built a string builder to add spaces into text if it is capital. The sentence entered would look like this : "ThisIsASentence." Since it starts with a capital, the string builder would modify the sentence to look like this: " This Is A Sentence."
My problem is, If I were to have a sentence like "thisIsASentence." the string builder will separate the sentence like normal : " this Is A Sentence."
Still both have a space in front of the first character.
When the sentence runs through this line:
result = result.Substring(1, 1).ToUpper() + result.Substring(2).ToLower();
If the first letter entered was lowercase, it gets cut off and the second letter becomes uppercase.
The line was meant to keep the first letter entered capitalized and set the rest lowercase.
Adding a trim statement before running that line changes nothing with the output.
Here is my overall code right now:
private void btnChange_Click(object sender, EventArgs e)
{
// New string named sentence, assigning the text input to sentence.
string sentence;
sentence = txtSentence.Text;
// String builder to let us modify string
StringBuilder sentenceSB = new StringBuilder();
/*
* For every character in the string "sentence" if the character is uppercase,
* add a space before the letter,
* if it isn't, add nothing.
*/
foreach (char c in sentence)
{
if (char.IsUpper(c))
{
sentenceSB.Append(" ");
}
sentenceSB.Append(c);
}
// Store the edited sentence into the "result" string
string result = sentenceSB.ToString();
// Starting at the 2nd spot and going 1, makes the first character capitalized
// Starting at position 3 and going to end change them to lower case.
result = result.Substring(1, 1).ToUpper() + result.Substring(2).ToLower();
// set the label text to equal "result" and set it visible.
lblChanged.Text = result.ToString();
lblChanged.Visible = true;
When you run the code with "thisIsASentence", After your foreach loop, result will be "this Is A Sentence", since it will not insert a space at the beginning.
Then your next line, will take the Character at index 1 (which is the 'h' in this), Make it uppercase, and then append the rest of the string, resulting in "His Is A Sentence"
To fix this, you can do result = result.Trim() after the loop, and then start at index 0, making the next line result = result.Substring(0, 1).ToUpper() + result.Substring(1).ToLower();
With result.SubString(1,1), you are assuming the first letter of the input is always capitalized, so your will always add a space in the beginning of the string. You have already seen that this isn't the case.
So I see basically two options for you:
Wrap that line in an if block that checks for spaces before replacing;
Capitalize the first letter of your input, if it's allowed by your spec.
I want to find number of letter "a" in only first sentence. The code below finds "a" in all sentences, but I want in only first sentence.
static void Main(string[] args)
{
string text; int k = 0;
text = "bla bla bla. something second. maybe last sentence.";
foreach (char a in text)
{
char b = 'a';
if (b == a)
{
k += 1;
}
}
Console.WriteLine("number of a in first sentence is " + k);
Console.ReadKey();
}
This will split the string into an array seperated by '.', then counts the number of 'a' char's in the first element of the array (the first sentence).
var count = Text.Split(new[] { '.', '!', '?', })[0].Count(c => c == 'a');
This example assumes a sentence is separated by a ., ? or !. If you have a decimal number in your string (e.g. 123.456), that will count as a sentence break. Breaking up a string into accurate sentences is a fairly complex exercise.
This is perhaps more verbose than what you were looking for, but hopefully it'll breed understanding as you read through it.
public static void Main()
{
//Make an array of the possible sentence enders. Doing this pattern lets us easily update
// the code later if it becomes necessary, or allows us easily to move this to an input
// parameter
string[] SentenceEnders = new string[] {"$", #"\.", #"\?", #"\!" /* Add Any Others */};
string WhatToFind = "a"; //What are we looking for? Regular Expressions Will Work Too!!!
string SentenceToCheck = "This, but not to exclude any others, is a sample."; //First example
string MultipleSentencesToCheck = #"
Is this a sentence
that breaks up
among multiple lines?
Yes!
It also has
more than one
sentence.
"; //Second Example
//This will split the input on all the enders put together(by way of joining them in [] inside a regular
// expression.
string[] SplitSentences = Regex.Split(SentenceToCheck, "[" + String.Join("", SentenceEnders) + "]", RegexOptions.IgnoreCase);
//SplitSentences is an array, with sentences on each index. The first index is the first sentence
string FirstSentence = SplitSentences[0];
//Now, split that single sentence on our matching pattern for what we should be counting
string[] SubSplitSentence = Regex.Split(FirstSentence, WhatToFind, RegexOptions.IgnoreCase);
//Now that it's split, it's split a number of times that matches how many matches we found, plus one
// (The "Left over" is the +1
int HowMany = SubSplitSentence.Length - 1;
System.Console.WriteLine(string.Format("We found, in the first sentence, {0} '{1}'.", HowMany, WhatToFind));
//Do all this again for the second example. Note that ideally, this would be in a separate function
// and you wouldn't be writing code twice, but I wanted you to see it without all the comments so you can
// compare and contrast
SplitSentences = Regex.Split(MultipleSentencesToCheck, "[" + String.Join("", SentenceEnders) + "]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
SubSplitSentence = Regex.Split(SplitSentences[0], WhatToFind, RegexOptions.IgnoreCase | RegexOptions.Singleline);
HowMany = SubSplitSentence.Length - 1;
System.Console.WriteLine(string.Format("We found, in the second sentence, {0} '{1}'.", HowMany, WhatToFind));
}
Here is the output:
We found, in the first sentence, 3 'a'.
We found, in the second sentence, 4 'a'.
You didn't define "sentence", but if we assume it's always terminated by a period (.), just add this inside the loop:
if (a == '.') {
break;
}
Expand from this to support other sentence delimiters.
Simply "break" the foreach(...) loop when you encounter a "." (period)
Well, assuming you define a sentence as being ended with a '.''
Use String.IndexOf() to find the position of the first '.'. After that, searchin a SubString instead of the entire string.
find the place of the '.' in the text ( you can use split )
count the 'a' in the text from the place 0 to instance of the '.'
string SentenceToCheck = "Hi, I can wonder this situation where I can do best";
//Here I am giving several way to find this
//Using Regular Experession
int HowMany = Regex.Split(SentenceToCheck, "a", RegexOptions.IgnoreCase).Length - 1;
int i = Regex.Matches(SentenceToCheck, "a").Count;
// Simple way
int Count = SentenceToCheck.Length - SentenceToCheck.Replace("a", "").Length;
//Linq
var _lamdaCount = SentenceToCheck.ToCharArray().Where(t => t.ToString() != string.Empty)
.Select(t => t.ToString().ToUpper().Equals("A")).Count();
var _linqAIEnumareable = from _char in SentenceToCheck.ToCharArray()
where !String.IsNullOrEmpty(_char.ToString())
&& _char.ToString().ToUpper().Equals("A")
select _char;
int a =linqAIEnumareable.Count;
var _linqCount = from g in SentenceToCheck.ToCharArray()
where g.ToString().Equals("a")
select g;
int a = _linqCount.Count();
I know how to capitalize first letter in each word. But I want to know how to capitalize first letter of each sentence in C#.
This is not necessarily a trivial problem. Sentences can end with a number of different punctuation marks, and those same punctuation marks don't always denote the end of a sentence (abbreviations like Dr. may pose a particular problem because there are potentially many of them).
That being said, you might be able to get a "good enough" solution by using regular expressions to look for words after a sentence-ending punctuation, but you would have to add quite a few special cases. It might be easier to process the string character by character or word by word. You would still have to handle all the same special cases, but it might be easier than trying to build that into a regex.
There are lots of weird rules for grammar and punctuation. Any solution you come up with probably won't be able to take them all into account. Some things to consider:
Sentences can end with different punctuation marks (. ! ?)
Some punctuation marks that end sentences might also be used in the middle of a sentence (e.g. abbreviations such as Dr. Mr. e.g.)
Sentences could contain nested sentences. Quotations could pose a particular problem (e.g. He said, "This is a hard problem! I wonder," he mused, "if it can be solved.")
As a first approximation, you could probably treat any sequence like [a-z]\.[ \n\t] as the end of a sentence.
Consider a sentence as a word containing spaces an ending with a period.
There's some VB code on this page which shouldn't be too hard to convert to C#.
However, subsequent posts point out the errors in the algorithm.
This blog has some C# code which claims to work:
It auto capitalises the first letter after every full stop (period), question mark and exclamation mark.
UPDATE 16 Feb 2010: I’ve reworked it so that it doesn’t affect strings such as URL’s and the like
Don't forget sentences with parentheses. Also, * if used as an idicator for bold text.
http://www.grammarbook.com/punctuation/parens.asp
I needed to do something similar, and this served my purposes. I pass in my "sentences" as a IEnumerable of strings.
// Read sentences from text file (each sentence on a separate line)
IEnumerable<string> lines = File.ReadLines(inputPath);
// Call method below
lines = CapitalizeFirstLetterOfEachWord(lines);
private static IEnumerable<string> CapitalizeFirstLetterOfString(IEnumerable<string> inputLines)
{
// Will output: Lorem lipsum et
List<string> outputLines = new List<string>();
TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
foreach (string line in inputLines)
{
string lineLowerCase = textInfo.ToLower(line);
string[] lineSplit = lineLowerCase.Split(' ');
bool first = true;
for (int i = 0; i < lineSplit.Length; i++ )
{
if (first)
{
lineSplit[0] = textInfo.ToTitleCase(lineSplit[0]);
first = false;
}
}
outputLines.Add(string.Join(" ", lineSplit));
}
return outputLines;
}
I know I'm little late, but just like You, I needed to capitalize every first character on each of my sentences.
I just fell here (and a lot of other pages while I was researching) and found nothing to help me out. So, I burned some neurons, and made a algorithm by myself.
Here is my extension method to capitalize sentences:
public static string CapitalizeSentences(this string Input)
{
if (String.IsNullOrEmpty(Input))
return Input;
if (Input.Length == 1)
return Input.ToUpper();
Input = Regex.Replace(Input, #"\s+", " ");
Input = Input.Trim().ToLower();
Input = Char.ToUpper(Input[0]) + Input.Substring(1);
var objDelimiters = new string[] { ". ", "! ", "? " };
foreach (var objDelimiter in objDelimiters)
{
var varDelimiterLength = objDelimiter.Length;
var varIndexStart = Input.IndexOf(objDelimiter, 0);
while (varIndexStart > -1)
{
Input = Input.Substring(0, varIndexStart + varDelimiterLength) + (Input[varIndexStart + varDelimiterLength]).ToString().ToUpper() + Input.Substring((varIndexStart + varDelimiterLength) + 1);
varIndexStart = Input.IndexOf(objDelimiter, varIndexStart + 1);
}
}
return Input;
}
Details about the algorithm:
This simple algorithm starts removing all double spaces. Then, it capitalize the first character of the string. then search for every delimiter. When find one, capitalize the very next character.
I made it easy to Add/Remove or Edit the delimiters, so You can change a lot how code works with a little change on it.
It doesn't check if the substrings go out of the string length, because the delimiters end with spaces, and the algorithm starts with a "Trim()", so every delimiter if found in the string will be followed by another character.
Important:
You didn't specify what were exactly your needs. I mean, it's a grammar corrector, it's just to prettify a text, etc... So, it's important to consider that my algorithm is just perfect for my needs, that can be different of yours.
*This algorithm was created to format a "Product Description" that isn't normalized (almost always it's entirely uppercased) in a nice format to the user (To be more specific, I need to show a pretty and "smaller" text for user. So, all characters in Upper Case is just opposite of what I want). So, it was not created to be grammatically perfect.
*Also, there maybe some exceptions where the character will not be uppercased because bad formatting.
*I choose to include spaces in the delimiter, so "http://www.stackoverflow.com" will not become "http://www.Stackoverflow.Com". In the other hand, sentences like "the box is blue.it's on the floor" will become "The box is blue.it's on the floor", and not "The box is blue.It's on the floor"
*In abbreviations cases, it will capitalize, but once again, it's not a problem because my needs is just show a product description (where grammar is not extremely critic). And in abbreviations like Mr. or Dr. the very first character is a name, so, it's perfect to be capitalized.
If You, or somebody else needs a more accurate algorithm, I'll be glad to improve it.
Hope I could help somebody!
However you can make a class or method to convert each text in TitleCase. Here is the example you just need to call the method.
public static string ToTitleCase(string strX)
{
string[] aryWords = strX.Trim().Split(' ');
List<string> lstLetters = new List<string>();
List<string> lstWords = new List<string>();
foreach (string strWord in aryWords)
{
int iLCount = 0;
foreach (char chrLetter in strWord.Trim())
{
if (iLCount == 0)
{
lstLetters.Add(chrLetter.ToString().ToUpper());
}
else
{
lstLetters.Add(chrLetter.ToString().ToLower());
}
iLCount++;
}
lstWords.Add(string.Join("", lstLetters));
lstLetters.Clear();
}
string strNewString = string.Join(" ", lstWords);
return strNewString;
}