Obviously I'm new to this, hence the content of this project. I have written some code that will translate English into Pig Latin. Easy enough. The problem is I want to find a way to translate the Pig Latin back into English using a logic block. The clone string just seems like a cheap way to do it. Any suggestions? Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FunctionTest
{
public class PigLatinClass
{
public static void pigTalk(string sentence)
{
try
{
while (sentence != "exit")
{
string firstLetter;
string afterFirst;
string pigLatinOut = "";
int x;
string vowel = "AEIOUaeiou";
Console.WriteLine("Enter a sentence to convert into PigLatin");
sentence = Console.ReadLine();
string[] pieces = sentence.Split();
foreach (string piece in pieces)
{
afterFirst = piece.Substring(1);
firstLetter = piece.Substring(0, 1);
x = vowel.IndexOf(firstLetter);
if (x == -1)
{
pigLatinOut = (afterFirst + firstLetter + "ay ");
}
else
{
pigLatinOut = (firstLetter + afterFirst + "way ");
}
Console.Write(pigLatinOut);
}
Console.WriteLine("Press Enter to flip the sentence back.");
Console.ReadKey(true);
string clonedString = null;
clonedString = (String)sentence.Clone();
Console.WriteLine(clonedString);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
The problem is there's no real rule that would work. For example: If the 3rd letter
from the last was "w" you might want to say this is a vowel word but, a consonant word starting with a "w" could also fit this rule. If the first letter was a vowel again you might want to say that this is a vowel word but, a consonant word could also fit this rule since the first letter is moved to the back (pat = atpay). The only way I think this is possible is to have an if statement that checks if w is in the 3rd position and the word starts with a vowel which would call for && operator and Visual Studio yells at you if you use it with strings.
The problem is that Pig Latin/English translation is not a bijective function.
For example, imagine to have 2 English words like "all" and "wall", the corresponding Pig Latin words will be always "allway".
This suggest you that if you get a word like "allway" you can't give a unique translation in English, but (at least) two.
I'm assuming this is homework.
What your professor probably wants is for you to convert a sentence to pig latin, and from pig latin. Keeping a copy of the original string only lets you "flip back" from sentences you already know the non-pig latin version of. It doesn't allow you to flip back from any string.
I think you want to structure your program like this:
public class PigLatinClass
{
public static string ToPigLatin(string sentence)
{
// Convert a string to pig latin
}
public static string FromPigLatin(string sentence)
{
// Convert a string from pig latin (opposite logic of above)
}
public static string PigTalk()
{
string sentence;
Console.WriteLine("Enter a sentence to convert into PigLatin");
sentence = Console.ReadLine();
sentence = ToPigLatin(sentence);
Console.WriteLine(sentence);
Console.WriteLine("Press Enter to flip the sentence back.");
Console.ReadKey(true);
sentence = FromPigLatin(sentence);
Console.WriteLine(sentence);
}
}
Related
string testSentence = "this is a test sentence and I WANT TO SEE HOW IT WILL LOOK LIKE hoping this part is big";
int firstLetter = testSentence.IndexOf("this");
int length = "this is a test sentence and".Length;
string upperSentence = testSentence.Substring(firstLetter, length).ToUpper();
int secondLetter = testSentence.IndexOf(" I");
int length2 = " I WANT TO SEE HOW IT WILL LOOK LIKE".Length;
string lowerSentence = testSentence.Substring(secondLetter, length2).ToLower();
int thirdSentence = testSentence.IndexOf(" hoping");
int length1 = " hoping this part is big".Length;
string get = testSentence.Substring(thirdSentence, length1).ToUpper();
Console.WriteLine(upperSentence + lowerSentence + get);
Can somebody please tell me how would you capitalize in all big or small letters only one word in the middle of the sentence? For example, make the word ''LOOK'' in small case letters. Does the ''.Length'' call has to be used or is there a different way than literally typing the word or part of the sentence that I want to convert to upper or lower cases?
The problem I have with this is, I cannot isolate just one word and make it low/big letters because then the rest of the string after the particular word is also in the lower/upper cases
In line with #Franck's advice, think about the problem as a human. You have three things:
a sentence
words that you want to be big
words that you want to be small
The sentence can really be broken down into a collection of words (ignoring punctuation). You want to go through the collection of words and change some of them to be uppercase and some of them to be lowercase - all the rest of the words you want to leave as they are.
Here is some code that does this:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
// modify these as you please
string testSentence = "this is a test sentence and I WANT TO SEE HOW IT WILL LOOK LIKE hoping this part is big";
string[] wordsToUpperCase = new string[] { "hoping", "test" };
string[] wordsToLowerCase = new string[] { "look", "is" };
// start processing
// split the sentence into words
string[] wordsInSentence = testSentence.Split(' ');
// a List to hold the reworked words
var outputWords = new System.Collections.Generic.List<string>();
// process the words
foreach (string currentWord in wordsInSentence)
{
// check the wordsToUpperCase array for the current word
bool shouldUpperCaseThisWord = wordsToUpperCase.Any(stringToTest => stringToTest.Equals(currentWord, StringComparison.CurrentCultureIgnoreCase));
// check the wordsToLowerCase array for the current word
bool shouldLowerCaseThisWord = wordsToLowerCase.Any(stringToTest => stringToTest.Equals(currentWord, StringComparison.CurrentCultureIgnoreCase));
// add the current word to the output list
if (shouldUpperCaseThisWord)
outputWords.Add(currentWord.ToUpper());
else if (shouldLowerCaseThisWord)
outputWords.Add(currentWord.ToLower());
else
outputWords.Add(currentWord);
}
string finalOutput = String.Join(" ", outputWords);
Console.WriteLine(finalOutput);
}
}
I was trying to create a list from a user input with something like this:
Create newlist: word1, word2, word3, etc...,
but how do I get those words one by one only by using commas as references going through them (in order) and placing them into an Array etc? Example:
string Input = Console.ReadLine();
if (Input.Contains("Create new list:"))
{
foreach (char character in Input)
{
if (character == ',')//when it reach a comma
{
//code goes here, where I got stuck...
}
}
}
Edit: I didn`t know the existence of "Split" my mistake... but at least it would great if you could explain me to to use it for the problem above?
You can use this:
String words = "word1, word2, word3";
List:
List<string> wordsList= words.Split(',').ToList<string>();
Array:
string[] namesArray = words.Split(',');
#patrick Artner beat me to it, but you can just split the input with the comma as the argument, or whatever you want the argument to be.
This is the example, and you will learn from the documentation.
using System;
public class Example {
public static void Main() {
String value = "This is a short string.";
Char delimiter = 's';
String[] substrings = value.Split(delimiter);
foreach (var substring in substrings)
Console.WriteLine(substring);
}
}
The example displays the following output:
Thi
i
a
hort
tring.
A palindrome is any string that is the same when read from start to end or backwards from end to start. For example, radar and solos are both palindromes.
How can code be written to determine if a string is a palindrome as well as count how often a specified letter exists within a string?
The following code determines if a string is a palindrome, but does not obtain the count of a specified character:
namespace oefening_2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Geef een random in: "); //console stel vraag
string sWrd = Console.ReadLine();//console slaagt woord op
Console.WriteLine("geef een random letter in: ");//console stele nog een vraagt
string sletter = Console.ReadLine();//console slaagt letter op
string sWoordOmge = ReverseString(sWrd);
IsPalin(sWrd, sWoordOmge);
Console.ReadLine();
}
//script
public static void IsPalin(string s1, string sWoordOmge)
{
if (s1 == sWoordOmge)
Console.Write("Het {0} is een palindroom", s1);//console geeft antwoord
else
Console.Write("Het {0} is geen palindroom", s1);//console geeft antwoord als het geen palindroom is
}
//berekeningen van console
public static string ReverseString(string s1)
{
string sWoordOmge = "";
for (int i = (s1.Length - 1); i >= 0; i--)
sWoordOmge += s1.Substring(i, 1);
return sWoordOmge;
}
}
}
If you are going to be asking questions on this site, then you will need to work harder on using English only. Mixing some English with Dutch does not work too well.
Another option to reverse a string is this code:
public static string ReverseString( string s )
{
char[] charArray = s.ToCharArray();
Array.Reverse( charArray );
return new string( charArray );
}
The problem with your reverse string method is that it creates a new string with each iteration - which is very inefficient for large strings. If you need to write a method that shows the mechanics of reversing a string, then another option would be to use the same logic in your method, but to use a StringBuilder object instead and then simply return the final string from StringBuilder's ToString method.
Here is my full solution to the problem:
public static void TestPalin()
{
// This method prompts the user for a word and a letter.
// It then determines whether or not the word is a palindrome and the number of times the letter appears in the palindrome.
//
Console.WriteLine("Enter a word: ");
string word = Console.ReadLine(); // Read in the word from the console.
Console.WriteLine("Enter a letter: ");
char letter = Console.ReadLine()[0]; // Read in the specified letter from the console.
int letterCount;
string reverseWord = ReverseAndGetCharCount(word, letter, out letterCount);
IsPalin(word, reverseWord, letter, letterCount);
Console.ReadLine();
}
public static void IsPalin(string word, string reverseWord, char letter, int letterCount)
{
// This method is used to display the result of the TestPalin method.
//
if (word == reverseWord)
Console.WriteLine($"The word {word} is a palindrome");
else
Console.WriteLine($"The word {word} is not a palindrome");
Console.WriteLine($"The letter {letter} appeared {letterCount} times within the word");
}
public static string ReverseAndGetCharCount(string s1, char selectedChar, out int countChar)
{
// This method reverses a string and counts the number of times the selected letter appears in the word.
//
char[] charArray = s1.ToCharArray();
char[] reverseArray = new char[s1.Length];
countChar = 0;
int j = 0;
char c;
for (int i = s1.Length - 1; i >= 0; i--)
{
c = charArray[i];
reverseArray[j++] = c;
if (c == selectedChar)
countChar++;
}
return new string(reverseArray);
}
Style wise, you should know that starting a variable with the type of class (also known as Hungarian notation) is out of vogue. So, variable names like sWrd should be simply named word instead.
You should get in the habit of writing a comment at the beginning of each method to give a brief description of what that method does. Don't describe how a method works in the comment, unless it is very complicated. Just briefly describe in a line or two what it is supposed to do.
Lastly, starting with C# 6, strings now have the capability to use string interpolation, which is indicated with the $ character. This produces clearer code with less typing.
My code should be translating a phrase into pig latin. Every word must have an "ay" at the end and every first letter of each word should be placed before "ay"
ex wall = "allway"
any ideas? this is the easiest way i could think of..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace english_to_pig_latin
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("THIS IS A English to Pig Latin translator");
Console.WriteLine("ENTER Phrase");
string[] phrase = Console.ReadLine().Split(' ');
int words = phrase.Length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words; i++)
{
//to add ay in the end
/*sb.Append(phrase[i].ToString());
sb.Append("ay ");
Console.WriteLine(sb);*/
}
Console.ReadLine();
}
}
}
First you need to define your pig-latin rules. your description lacks real pig-latin rules. for instance, English "sharp" is correctly "Pig-Latinized" as 'arpshay', not 'harpsay', as your explanation above explained. (But i prefer to use 'arp-sh-ay' to facilitate reading of PigLatin as well as using hyphens make it possible to reverse translate back into English.) i suggest you first find some rules for Pig-Latin. Your start is a good start. Your code now separates a phrase into (almost) words. Note that your code will turn "Please, Joe" into "Please," and "Joe" tho, and you probably do not want that comma sent to your word-by-word translator.
when defining your rules, i suggest you consider how to Pig-Latin-ize these words:
hello --> 'ellohay' (a normal word),
string --> 'ingstray' ('str' is the whole consonant string moved to the end),
apple --> 'appleway', 'appleay', or 'appleyay', (depending on your dialect of Pig-Latin),
queen --> 'eenquay' ('qu' is the consonant string here),
yellow --> 'ellowyay' (y is consonant here),
rhythm --> 'ythmrhay' (y is vowel here),
sky --> 'yskay' (y is vowel here).
Note that for any word that starts with 'qu' (like 'queen'), this 'qu' is a special condition that needs handled too. Note that y is probably a consonant when it begins an English word, but a vowel when in the middle or at the end of a word.
The hyphenated Pig Latin versions of these words would be:
ello-h-ay, ing-str-ay, ('apple-way', 'apple-ay', or 'apple-yay'), 'een-qu-ay', 'ellow-y-ay', 'ythm-rh-ay', and 'y-sk-ay'. The hyphenation allows both easier reading as well as an ability to reverse the Pig Latin back into English by a computer parser. But unfortunately, many people just cram the Pig Latin word together without showing any hyphenation separation, so reversing the translation cannot be done simply without ambiguity.
Real pig-latin really goes by the sound of the word, not the spelling, so without a very complex word to phoneme system, this is way too difficult. but most (good) pig-latin writing translators handle the above cases and ignore other exceptions because English is really a very bad language when it comes to phonetically sounding out words.
So my first suggestion is get a set of rules. my 2nd suggestion is use two functions, PigLatinizePhrase() and PigLatinizeWord() where your PigLatinizePhrase() method parses a phrase into words (and punctuation), and calls PigLatinizeWord() for each word, excluding any punctuation. you can use a simple loop thru each character and test for char.IsLetter to determine if it's a letter or not. if it's a letter then add it to a string builder and move to the next letter. if it's not a letter and the string builder is not empty then send that word to your word parser to parse it, and then add the non-letter to your result. this would be your logic for your PigLatinizePhrase() method. Here is my code which does just that:
/// <summary>
/// </summary>
/// <param name="eng">English text, paragraphs, etc.</param>
/// <param name="suffixWithNoOnset">Used to differentiate between Pig Latin dialects.
/// Known dialects may use any of: "ay", "-ay", "way", "-way", "yay", or "-yay".
/// Cooresponding translations for 'egg' will yield: "eggay", "egg-ay", "eggway", "egg-way", "eggyay", "egg-yay".
/// Or for 'I': "Iay", "I-ay", "Iway", "I-way", "Iyay", "I-yay".
/// </param>
/// <returns></returns>
public static string PigLatinizePhrase(string eng, string suffixWithNoOnset = "-ay")
{
if (eng == null) { return null; } // don't break if null
var word = new StringBuilder(); // only current word, built char by char
var pig = new StringBuilder(); // pig latin text
char prevChar = '\0';
foreach (char thisChar in eng)
{
// the "'" test is so "I'll", "can't", and "Ashley's" will work right.
if (char.IsLetter(thisChar) || thisChar == '\'')
{
word.Append(thisChar);
}
else
{
if (word.Length > 0)
{
pig.Append(PigLatinizeWord(word.ToString(), suffixWithNoOnset));
word = new StringBuilder();
}
pig.Append(thisChar);
}
prevChar = thisChar;
}
if (word.Length > 0)
{
pig.Append(PigLatinizeWord(word.ToString(), suffixWithNoOnset));
}
return pig.ToString();
} // public static string PigLatinizePhrase(string eng, string suffixWithNoOnset = "-ay")
The suffixWithNoOnset variable is simply passed directly to the PigLatinizeWord() method and it determines exactly which 'dialect' of Pig Latin will be used. (See the XML comment before the method in the source code for more clarity.)
For the PigLatinizeWord() method, upon actually programming it, i found that it was very convenient to split this functionality into two methods, one method to parse the English word into the 2 parts that Pig Latin cares about, and another to actually do what is desired with those 2 parts, depending on which version of Pig Latin is desired. Here's the source code for these two functions:
/// <summary>
/// </summary>
/// <param name="eng">English word before being translated to Pig Latin.</param>
/// <param name="suffixWithNoOnset">Used to differentiate between Pig Latin dialects.
/// Known dialects may use any of: "ay", "-ay", "way", "-way", "yay", or "-yay".
/// Cooresponding translations for 'egg' will yield: "eggay", "egg-ay", "eggway", "egg-way", "eggyay", "egg-yay".
/// Or for 'I': "Iay", "I-ay", "Iway", "I-way", "Iyay", "I-yay".
/// </param>
/// <returns></returns>
public static string PigLatinizeWord(string eng, string suffixWithNoOnset = "-ay")
{
if (eng == null || eng.Length == 0) { return eng; } // don't break if null or empty
string[] onsetAndEnd = GetOnsetAndEndOfWord(eng);
// string h = string.Empty;
string o = onsetAndEnd[0]; // 'Onset' of first syllable that gets moved to end of word
string e = onsetAndEnd[1]; // 'End' of word, without the onset
bool hyphenate = suffixWithNoOnset.Contains('-');
// if (hyphenate) { h = "-"; }
var sb = new StringBuilder();
if (e.Length > 0) { sb.Append(e); if (hyphenate && o.Length > 0) { sb.Append('-'); } }
if (o.Length > 0) { sb.Append(o); if (hyphenate) { sb.Append('-'); } sb.Append("ay"); }
else { sb.Append(suffixWithNoOnset); }
return sb.ToString();
} // public static string PigLatinizeWord(string eng)
public static string[] GetOnsetAndEndOfWord(string word)
{
if (word == null) { return null; }
// string[] r = ",".Split(',');
string uppr = word.ToUpperInvariant();
if (uppr.StartsWith("QU")) { return new string[] { word.Substring(0,2), word.Substring(2) }; }
int x = 0; if (word.Length <= x) { return new string[] { string.Empty, string.Empty }; }
if ("AOEUI".Contains(uppr[x])) // tests first letter/character
{ return new string[] { word.Substring(0, x), word.Substring(x) }; }
while (++x < word.Length)
{
if ("AOEUIY".Contains(uppr[x])) // tests each character after first letter/character
{ return new string[] { word.Substring(0, x), word.Substring(x) }; }
}
return new string[] { string.Empty, word };
} // public static string[] GetOnsetAndEndOfWord(string word)
I have written a PigLatinize() method in JavaScript before, which was a lot of fun for me. :) I enjoyed making my C# version with more features, giving it the ability to translate to 6 varyious 'dialects' of Pig Latin, especially since C# is my favorite (programming) language. ;)
I think you need this transformation: phrase[i].Substring(1) + phrase[i][0] + "ay"
I could write my own algorithm to do it, but I feel there should be the equivalent to ruby's humanize in C#.
I googled it but only found ways to humanize dates.
Examples:
A way to turn "Lorem Lipsum Et" into "Lorem lipsum et"
A way to turn "Lorem lipsum et" into "Lorem Lipsum Et"
As discussed in the comments of #miguel's answer, you can use TextInfo.ToTitleCase which has been available since .NET 1.1. Here is some code corresponding to your example:
string lipsum1 = "Lorem lipsum et";
// Creates a TextInfo based on the "en-US" culture.
TextInfo textInfo = new CultureInfo("en-US",false).TextInfo;
// Changes a string to titlecase.
Console.WriteLine("\"{0}\" to titlecase: {1}",
lipsum1,
textInfo.ToTitleCase( lipsum1 ));
// Will output: "Lorem lipsum et" to titlecase: Lorem Lipsum Et
It will ignore casing things that are all caps such as "LOREM LIPSUM ET" because it is taking care of cases if acronyms are in text so that "IEEE" (Institute of Electrical and Electronics Engineers) won't become "ieee" or "Ieee".
However if you only want to capitalize the first character you can do the solution that is over hereā¦ or you could just split the string and capitalize the first one in the list:
string lipsum2 = "Lorem Lipsum Et";
string lipsum2lower = textInfo.ToLower(lipsum2);
string[] lipsum2split = lipsum2lower.Split(' ');
bool first = true;
foreach (string s in lipsum2split)
{
if (first)
{
Console.Write("{0} ", textInfo.ToTitleCase(s));
first = false;
}
else
{
Console.Write("{0} ", s);
}
}
// Will output: Lorem lipsum et
There is another elegant solution :
Define the function ToTitleCase in an static class of your projet
using System.Globalization;
public static string ToTitleCase(this string title)
{
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(title.ToLower());
}
And then use it like a string extension anywhere on your project:
"have a good day !".ToTitleCase() // "Have A Good Day !"
Use regular expressions for this looks much cleaner:
string s = "the quick brown fox jumps over the lazy dog";
s = Regex.Replace(s, #"(^\w)|(\s\w)", m => m.Value.ToUpper());
All the examples seem to make the other characters lowered first which isn't what I needed.
customerName = CustomerName <-- Which is what I wanted
this is an example = This Is An Example
public static string ToUpperEveryWord(this string s)
{
// Check for empty string.
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
var words = s.Split(' ');
var t = "";
foreach (var word in words)
{
t += char.ToUpper(word[0]) + word.Substring(1) + ' ';
}
return t.Trim();
}
If you just want to capitalize the first character, just stick this in a utility method of your own:
return string.IsNullOrEmpty(str)
? str
: str[0].ToUpperInvariant() + str.Substring(1).ToLowerInvariant();
There's also a library method to capitalize the first character of every word:
http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx
CSS technique is ok but only changes the presentation of the string in the browser. A better method is to make the text itself capitalised before sending to browser.
Most of the above implimentations are ok, but none of them address the issue of what happens if you have mixed case words that need to be preserved, or if you want to use true Title Case, for example:
"Where to Study PHd Courses in the USA"
or
"IRS Form UB40a"
Also using CultureInfo.CurrentCulture.TextInfo.ToTitleCase(string) preserves upper case words as in
"sports and MLB baseball" which becomes "Sports And MLB Baseball" but if the whole string is put in upper case, then this causes an issue.
So I put together a simple function that allows you to keep the capital and mixed case words and make small words lower case (if they are not at the start and end of the phrase) by including them in a specialCases and lowerCases string arrays:
public static string TitleCase(string value) {
string titleString = ""; // destination string, this will be returned by function
if (!String.IsNullOrEmpty(value)) {
string[] lowerCases = new string[12] { "of", "the", "in", "a", "an", "to", "and", "at", "from", "by", "on", "or"}; // list of lower case words that should only be capitalised at start and end of title
string[] specialCases = new string[7] { "UK", "USA", "IRS", "UCLA", "PHd", "UB40a", "MSc" }; // list of words that need capitalisation preserved at any point in title
string[] words = value.ToLower().Split(' ');
bool wordAdded = false; // flag to confirm whether this word appears in special case list
int counter = 1;
foreach (string s in words) {
// check if word appears in lower case list
foreach (string lcWord in lowerCases) {
if (s.ToLower() == lcWord) {
// if lower case word is the first or last word of the title then it still needs capital so skip this bit.
if (counter == 0 || counter == words.Length) { break; };
titleString += lcWord;
wordAdded = true;
break;
}
}
// check if word appears in special case list
foreach (string scWord in specialCases) {
if (s.ToUpper() == scWord.ToUpper()) {
titleString += scWord;
wordAdded = true;
break;
}
}
if (!wordAdded) { // word does not appear in special cases or lower cases, so capitalise first letter and add to destination string
titleString += char.ToUpper(s[0]) + s.Substring(1).ToLower();
}
wordAdded = false;
if (counter < words.Length) {
titleString += " "; //dont forget to add spaces back in again!
}
counter++;
}
}
return titleString;
}
This is just a quick and simple method - and can probably be improved a bit if you want to spend more time on it.
if you want to keep the capitalisation of smaller words like "a" and "of" then just remove them from the special cases string array. Different organisations have different rules on capitalisation.
You can see an example of this code in action on this site: Egg Donation London - this site automatically creates breadcrumb trails at the top of the pages by parsing the url eg "/services/uk-egg-bank/introduction" - then each folder name in the trail has hyphens replaced with spaces and capitalises the folder name, so uk-egg-bank becomes UK Egg Bank. (preserving the upper case 'UK')
An extension of this code could be to have a lookup table of acronyms and uppercase/lowercase words in a shared text file, database table or web service so that the list of mixed case words can be maintained from one single place and apply to many different applications that rely on the function.
There is no prebuilt solution for proper linguistic captialization in .NET. What kind of capitialization are you going for? Are you following the Chicago Manual of Style conventions? AMA or MLA? Even plain english sentence capitalization has 1000's of special exceptions for words. I can't speak to what ruby's humanize does, but I imagine it likely doesn't follow linguistic rules of capitalization and instead does something much simpler.
Internally, we encountered this same issue and had to write a fairly large amount code just to handle proper (in our little world) casing of article titles, not even accounting for sentence capitalization. And it indeed does get "fuzzy" :)
It really depends on what you need - why are you trying to convert the sentences to proper capitalization (and in what context)?
I have achieved the same using custom extension methods. For First Letter of First sub-string use the method yourString.ToFirstLetterUpper(). For First Letter of Every sub-string excluding articles and some propositions, use the method yourString.ToAllFirstLetterInUpper(). Below is a console program:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("this is my string".ToAllFirstLetterInUpper());
Console.WriteLine("uniVersity of lonDon".ToAllFirstLetterInUpper());
}
}
public static class StringExtension
{
public static string ToAllFirstLetterInUpper(this string str)
{
var array = str.Split(" ");
for (int i = 0; i < array.Length; i++)
{
if (array[i] == "" || array[i] == " " || listOfArticles_Prepositions().Contains(array[i])) continue;
array[i] = array[i].ToFirstLetterUpper();
}
return string.Join(" ", array);
}
private static string ToFirstLetterUpper(this string str)
{
return str?.First().ToString().ToUpper() + str?.Substring(1).ToLower();
}
private static string[] listOfArticles_Prepositions()
{
return new[]
{
"in","on","to","of","and","or","for","a","an","is"
};
}
}
OUTPUT
This is My String
University of London
Process finished with exit code 0.
Far as I know, there's not a way to do that without writing (or cribbing) code. C# nets (ha!) you upper, lower and title (what you have) cases:
http://support.microsoft.com/kb/312890/EN-US/