The Input is 3.3 is a double
and the output I should get 3.3 isway away oubleday
but instead I am getting .33ay isway away oubleday
.
Does anyone know why ?
Console.WriteLine("Give a sentence: ");
string sentence = Console.ReadLine();
string pigLatin = ToPigLatin(sentence);
Console.WriteLine(pigLatin);
static string ToPigLatin(string sentence)
{
const string vowels = "AEIOUYaeioy";
List<string> pigWords = new List<string>();
foreach (string word in sentence.Split(' '))
{
string firstLetter = word.Substring(0, 1);
string restOfWord = word.Substring(1, word.Length - 1);
int currentLetter = vowels.IndexOf(firstLetter);
if (currentLetter == -1)
{
pigWords.Add(restOfWord firstLetter "ay");
}
else
{
pigWords.Add(word "way");
}
}
return string.Join(" ", pigWords);
}
CodePudding user response:
Consider ignoring numbers:
if(double.TryParse(word, out var _))
pigWords.Add(word);
else if (currentLetter == -1)
pigWords.Add(restOfWord firstLetter "ay");
else
pigWords.Add(word "way");
CodePudding user response:
The main problem with your approach, IMHO, is that you should translate words like is
, double
, but keep intact numbers like 3.3
, punctuations etc. string.Split(...)
is not powerful enough. In order to replace words only, we can use a simple regular expression:
using System.Text.Regular.Expressions;
...
string result = Regex.Replace(text, "[A-Za-z] ", m => WordToPigLatin(m.Value));
here WordToPigLatin
have only to operate with proper words only and that's why much easier to implement:
static string WordToPigLatin(string value) {
const string vowels = "AEIOUYaeioy";
if (vowels.Contains(value[0]))
return value "way";
string prefix = string.Concat(value.TakeWhile(c => !vowels.Contains(c)));
return value.Substring(prefix.Length) prefix "ay";
}
Combining it all together
Code:
using System.Linq;
using System.Text.Regular.Expressions;
...
private static string ToPigLatin(string text) {
if (string.IsNullOrEmpty(text))
return text;
static string WordToPigLatin(string value) {
const string vowels = "AEIOUYaeioy";
if (vowels.Contains(value[0]))
return value "way";
string prefix = string.Concat(value.TakeWhile(c => !vowels.Contains(c)));
return value.Substring(prefix.Length) prefix "ay";
}
return Regex.Replace(text, "[A-Za-z] ", m => WordToPigLatin(m.Value));
}
Demo:
string demo = "3.3 is a double, - not an integer (!) like 1 or -5";
Console.Write(ToPigLatin(demo));
Outcome:
3.3 isway away oubleday, - otnay anway integerway (!) ikelay 1 orway -5