I'm having some trouble making an applicaton in c# converting english to pig latin. I have everything else down except for when it comes to making the getTranslation method for it. For some odd reason I just can't figure it out. IF someone could give me some ideas I would appreciate it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace W15M5A2_CPigLatinApp
{
class W15M5A2_CPigLatinAppProgram
{
static void Main(string[] args)
{
string inputPhrase = "";
string[] phraseOut;
DisplayInfo();
inputPhrase = GetPhrase();
while (inputPhrase != "")
{
Console.WriteLine(" ");
phraseOut = GetTranslation(inputPhrase);
DisplayResults(inputPhrase, phraseOut);
inputPhrase = GetPhrase();
}
Console.ReadKey();
}
public static void DisplayInfo()
{
Console.WriteLine("********************************************************" +
"\n*** You will be prompted to enter a string of ***" +
"\n*** words. The phrase will be converted into a ***" +
"\n*** pseudo Pig Latin with results displayed. ***" +
"\n\n*** Enter as many strings as you would like. ***" +
"\n********************************************************\n\n");
Console.Write("\n\n\n Press any key when you are ready to begin...");
Console.ReadKey();
Console.Clear();
}
public static string GetPhrase()
{
string inputPhrase;
Console.WriteLine("Enter a phrase or group of words " +
"\nTo Exit, press the Enter key\n");
inputPhrase = Console.ReadLine();
return inputPhrase;
}
// GetTranslation method
public static string[] GetTranslation(string phraseIn)
{
}
public static void DisplayResults(string input, string[] output)
{
Console.Clear();
Console.WriteLine("Original Phrase: " + input + "\n");
Console.Write("\nNew Phrase: ");
foreach (string i in output)
{
Console.Write(i + " ");
}
Console.WriteLine("\n");
}
}
}
public static string[] GetTranslation(string phraseIn)
{
string vow = "aeiouyAEIOUY";
var splitted = phraseIn.Split(new[] {" "}, StringSplitOptions.None);
List< string> ret = new List<string>();
foreach (string split in splitted)
{
string vows = string.Empty;
string cons = string.Empty;
for (var i = 0; i < split.Length; i++)
{
char ch = split[i];
if (vow.Contains(ch))
{
vows += ch;
}
else
{
cons += ch;
}
}
ret.Add(cons + vows + "ay");
}
return ret.ToArray();
}
This is a (little bit hacky) solution. I tested it with the examples from Wiki.
public static string ToPigLatin(string word)
{
string result = string.Empty;
string pigSuffixVowelFirst = "yay";
string pigSuffixConstanantsFirst = "ay";
string vowels = "aeiouAEIOU";
if(vowels.Contains(word.First()))
{
result = word + pigSuffixVowelFirst;
}
else
{
int count = 0;
string end = string.Empty;
foreach(char c in word)
{
if (!vowels.Contains(c))
{
end += c;
count++;
}
else
{
break;
}
}
result = word.Substring(count) + end + pigSuffixConstanantsFirst;
}
return result;
}
Use at your own peril :)
Related
I want to print the 3 lines of characters in reversed order but this example is done simply. How can I do it with foreach loop without using arrays?
public static void Main()
{
char firstInput = char.Parse(Console.ReadLine());
char secondInput = char.Parse(Console.ReadLine());
char thirdInput = char.Parse(Console.ReadLine());
Console.WriteLine(thirdInput.ToString() + " " + secondInput.ToString() + " " + firstInput.ToString());
}
You could create a method using the params keyword - not tested but something like:
private static string ReverseOrder(params char[] characters)
{
var result = "";
for (int i = characters.count; i > 0; i--)
{
result = result + characters[i];
}
return result;
}
and call like:
var reverseOrderResult = ReverseOrder(firstinput, secondinput, thirdinput);
Here's an attempt to follow the input conditions: no arrays and use of foreach loop (I'm sure the author isn't looking for something like this)
static void Main()
{
var result = "";
foreach (var c in NextInput(3))
{
result = c + " " + result;
}
Console.WriteLine(result);
}
private static IEnumerable<char> NextInput(int count)
{
var i = 0;
while (i++ < count)
yield return char.Parse(Console.ReadLine());
}
I want to create simple console wingman game.My error is that if i try get pos of 2 same character in word i get only one and the other is skipped.
For example Tomatoe.
Console output:
Tomatoe
_ o m a t _ _
I know i didnt use live didnt have time for that i do it layter.
class Program {
static string[] word = { "Pineapple", "Apple" , "Tomatoe" , "Pizza"};
static int wordIndex = 0;
static char[] randomWord;
static bool guessing = true;
public static void Main(string[] args)
{
int lives = 3;
Console.OutputEncoding = Encoding.UTF8;
Console.InputEncoding = Encoding.UTF8;
Random r = new Random();
wordIndex = r.Next(word.Length);
randomWord = word[wordIndex].ToLower().ToCharArray();
char[] randomWordcensored = new char[randomWord.Length];
for (int i = 0; i < randomWord.Length; i++)
{
randomWordcensored[i] = '_';
}
Console.WriteLine("Hello");
foreach (var item in randomWordcensored)
{
Console.Write(item + " ");
}
Console.WriteLine();
Console.WriteLine("Please Enter character:");
while (guessing = true)
{
int g = 0;
char userinput;
bool security = char.TryParse(Console.ReadLine() ,out userinput);
if (security == true) {
if (randomWord.Contains(userinput))
{ //help needed
g = (word[wordIndex].ToString().IndexOf(userinput) == -1 ? 0 : word[wordIndex].ToString().IndexOf(userinput));
randomWordcensored[g] = userinput;
Console.WriteLine("Good :) " + g);
foreach (var item in randomWordcensored)
{
Console.Write(item + " ");
}
}
else
{
lives--;
Console.WriteLine("Wrong!\n-Lives:" + lives);
}
}
else
{
Console.WriteLine("Enter only one charracter!");
}
}
}
}
You'll want to handle user input that might be different casing and such. Because of that it's easiest to just visit every character in the random word just once.
Here's a REPL that I made to solve this:
using System;
using System.Collections.Generic;
class MainClass {
public static void Main (string[] args) {
var word = "Tomato";
var input = "t";
var letter = input.ToLower()[0];
var indices = new List<int>();
for(var i = 0; i < word.Length; i++)
if (word.ToLower()[i] == letter)
indices.Add(i);
Console.WriteLine($"Secret word: {word}");
Console.WriteLine($"User guess: {input}");
Console.WriteLine($"Found at {String.Join(", ", indices)}");
}
}
and its output:
Mono C# compiler version 4.0.4.0
Secret word: Tomato
User guess: t
Found at 0, 4
The whole program is listed after, but the only problem i have with it is the ToUppers() method. I just want this method to iterate over each string in my array, and then make everything upper case.
private static string[] ToUppers(string[] stringToUpperArrays)
{
string stringer;
foreach (string value in stringToUpperArrays)
{
stringer = value.ToUpper(); // <== this line highlighted
Console.WriteLine(stringer);
}
return stringToUpperArrays;
}
The program executes after it prints it on the console, and it lists a NullReferenceException, and highlights the stringer = value.ToUpper(); line
The whole program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utility;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//Mark Bouwman
//CNT A01
//ICA18
//April 2nd
string answer;
int numInArray;
string[] stringArrays;
string[] stringArraysToDisplay;
string[] stringToUpperArrays;
//TITLE
Console.WriteLine("\t\tStringy");
do
{
numInArray = Utility.Utility.GetInt(2, 10, "Enter the size of the array from 2 to 10: ");
stringArrays = CreateArray(numInArray);
stringArraysToDisplay = Display(stringArrays);
stringToUpperArrays = ToUppers(stringArrays);
//aksing to run program again
Console.Write("Run program again? yes or no: ");
answer = Console.ReadLine();
}
while (answer.Equals("yes", StringComparison.CurrentCultureIgnoreCase));
}
private static string[] CreateArray(int numInArray)
{
int index;
string[] stringArray;
stringArray = new string[(numInArray + 1)];
for (index = 0; index < numInArray; ++index)
{
Console.Write("Enter string #" + (index + 1) + " ");
stringArray[index] = Console.ReadLine();
}
return stringArray;
}
private static string[] Display(string[] stringArraysDisplay)
{
foreach (string value in stringArraysDisplay)
{
Console.WriteLine(value);
}
return stringArraysDisplay;
}
private static string[] ToUppers(string[] stringToUpperArrays)
{
string stringer;
foreach (string value in stringToUpperArrays)
{
stringer = value.ToUpper();
Console.WriteLine(stringer);
}
return stringToUpperArrays;
}
}
}
In CreateArray you define the array to size of numInArray + 1 but you fill the array only with numInArray strings, i.e. the last index is empty. When you try value.ToUpper(); on the empty index you get the exception.
In CreateArray change
stringArray = new string[(numInArray + 1)];
To
stringArray = new string[numInArray];
Or change
for (index = 0; index < numInArray; ++index)
{
Console.Write("Enter string #" + (index + 1) + " ");
stringArray[index] = Console.ReadLine();
}
To
for (index = 0; index < stringArray.Length; ++index)
{
Console.Write("Enter string #" + (index + 1) + " ");
stringArray[index] = Console.ReadLine();
}
You should erase the + 1 when you are initializing the array
stringArray = new string[(numInArray)];
in this method
private static string[] CreateArray(int numInArray)
This is my code for some console app. First thing that doesn't work very well is method SwitchLetters. When I input some string and press enter every letter goes to new line. I don't know why. Also i don't know how to display lower and upper case in methods PrintBeforeSwitch and PrintAfterSwitch. And Exception how to use try and catch for some exception and which exception to use...
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please input string");
string input = Console.ReadLine();
NewString ns = new NewString();
StringOperation so = new StringOperation();
ns.SwitchLetters(input);
so.PrintBeforeSwitch(input);
so.PrintAfterSwitch(input);
}
}
class NewString
{
private string newString;
public string _NewString
{
get
{
return newString;
}
set
{
newString = value;
}
}
public void SwitchLetters(string newStr)
{
StringBuilder myString = new StringBuilder();
for (int i = 0; i < newStr.Length; i++)
{
if (char.IsUpper(newStr, i))
myString.Append(char.ToLower(newStr[i]));
else if (char.IsLower(newStr, i))
myString.Append(char.ToUpper(newStr[i]));
else
myString.Append(newStr[i]);
Console.WriteLine(myString.ToString());
Console.ReadLine();
Console.WriteLine(newStr.ToUpper());
}
}
}
class StringOperation
{
private string inputString;
//public NewString newSrt;
public string InputString
{
get
{
return inputString;
}
set
{
inputString = value;
}
}
public int VocalNumber(string str)
{
int num;
return num = str.Count(a => "aeiouAEIOU".Contains(a));
}
public int SpaceNumber(string str)
{
int num;
return num = str.Count(b => b == ' ');
}
public List<int> LowerUpperCaseLattersNumber(string str)
{
int counterLower = 0;
int counterUpper = 0;
List<int> counter = new List<int>();
foreach (char value in str)
{
if (char.IsLower(value))
{
counterLower++;
}
else
{
counterUpper++;
}
}
counter.Add(counterLower);
counter.Add(counterUpper);
Console.WriteLine("Number of small latters is: {0}", counterLower);
Console.WriteLine("Number of big letters is: {0}", counterUpper);
return counter;
}
public string SwitchVocals(ref string str)
{
string vocals = str.Replace("a", "x").Replace("e", "x").Replace("i", "x").Replace("o", "x").Replace("u", "x").Replace("A", "X").Replace("E", "X").Replace("I", "X").Replace("O", "X").Replace("U", "X");
Console.WriteLine(vocals);
return vocals;
}
public void PrintBeforeSwitch(string str)
{
Console.WriteLine(str);
Console.WriteLine("Information about string:");
Console.WriteLine("Number of vowels: {0}", VocalNumber(str));
Console.WriteLine("Number of space: {0}", SpaceNumber(str));
Console.WriteLine("Number of small latters is: {0}", LowerUpperCaseLattersNumber(str));
Console.WriteLine("Number of big letters is: {0}", LowerUpperCaseLattersNumber(str));
Console.ReadLine();
}
public void PrintAfterSwitch(string str)
{
SwitchVocals(ref str);
Console.WriteLine("Information about string after switch:");
Console.WriteLine("Number of vowels: {0}", VocalNumber(str));
Console.WriteLine("Number of space: {0}", SpaceNumber(str));
Console.WriteLine("Number of small latters is: {0}", LowerUpperCaseLattersNumber(str));
Console.WriteLine("Number of big letters is: {0}", LowerUpperCaseLattersNumber(str));
Console.ReadLine();
}
}
Here is an idea how to do the exception:
public void SwitchLetters(string newStr)
{
try
{
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();//this stops the program so you can read the error
}
}
I think you had the two lines swapped around so.PrintBeforeSwitch and ns.SwitchLetters
static void Main(string[] args)
{
Console.WriteLine("Please input string");
string input = Console.ReadLine();
NewString ns = new NewString();
StringOperation so = new StringOperation();
so.PrintBeforeSwitch(input);
ns.SwitchLetters(input);
so.PrintAfterSwitch(input);
}
If you use Console.WriteLine("some string here"); it will do exactly as it says, write line. However you can use Console.Write("some string here"); and it should add the text/string onto the existing line.
Can you please give us more information by what you mean "First thing that doesn't work very well is method SwitchLetters..." what should it do? What does it currently do?
To resolve your issue in the comment below remove the Console.ReadLine()
public void SwitchLetters(string newStr)
{
StringBuilder myString = new StringBuilder();
for (int i = 0; i < newStr.Length; i++)
{
if (char.IsUpper(newStr, i))
myString.Append(char.ToLower(newStr[i]));
else if (char.IsLower(newStr, i))
myString.Append(char.ToUpper(newStr[i]));
else
myString.Append(newStr[i]);
Console.WriteLine(myString.ToString());
//Console.ReadLine(); This line needs to be removed
Console.WriteLine(newStr.ToUpper());
}
}
I need help with a program that im using to verify a user's names. there has to be a certain level of leniency to accept differences like hyphens, spaces and apostrophes. Currently im removing useless characters to compare the strings but names of completely different characters with the same length are being Ok'd. how do i check to see the names are suing similar characters. after the useless ones have been removed and mushed together.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace name_v
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter first name");
string firstname = Console.ReadLine();
Console.WriteLine("Enter 2nd name");
string secondname = Console.ReadLine();
if (firstname == secondname)
{
Console.WriteLine("Names are exactly the same");
Console.ReadLine();
}
else
{
Console.WriteLine("press enter to Compare");
Console.ReadLine();
int numFirstName = firstname.Length;
int numSecondName = secondname.Length;
Console.WriteLine("# in 1st = " + numFirstName);
Console.WriteLine("# in 2nd = " + numSecondName);
Console.ReadLine();
firstname = firstname.Replace(" ", "").Replace("-", "").Replace("'", "").Replace(".", "").ToUpper();
secondname = secondname.Replace(" ", "").Replace("-", "").Replace("'", "").Replace(".", "").ToUpper();
Console.WriteLine("Names to be compared as");
Console.WriteLine(firstname);
Console.WriteLine(secondname);
numFirstName = firstname.Length;
numSecondName = secondname.Length;
Console.WriteLine("# in 1st = " + numFirstName);
Console.WriteLine("# in 2nd = " + numSecondName);
Console.ReadLine();
int nameLengthDif = numFirstName - numSecondName;
if (firstname == secondname)
{
Console.WriteLine("Names are the same");
Console.ReadLine();
}
else
{
Console.WriteLine("Names are not the same");
Console.ReadLine();
if (nameLengthDif < 3)
{
Console.WriteLine("But Close enough");
Console.ReadLine();
}
else
{
Console.WriteLine("And not Close enough");
Console.ReadLine();
}
}
}
}
}
}
#TestWell gave a great solution for determining character difference, but I just want to show you a much better way to strip characters than stringing .Replace() over and over and over again:
You can just add/remove chars from this array:
private char[] invalid = new char[] {' ','-','_','.'};
private static string cleanString(string input)
{
return new string(input.Where(x => !invalid.Contains(x)).ToArray()).ToLower();
}
usage:
firstname = cleanString(firstname);
or as an extension method:
namespace CustomExtensions
{
public static class StringExtension
{
private static char[] invalid = new char[] {' ','-','_','.'};
public static string CleanString(this string y)
{
return new string(y.Where(x => !invalid.Contains(x)).ToArray()).ToLower();
}
}
}
usage:
firstname = firstname.CleanString();
try as following :
char[] firstName = firstName.ToCharArray();
char[] lastName = lastName.ToCharArray();
char[] res = firstName.Except(lastName).ToArray();
if(res.Length < 1)
{
res = lastName.Except(firstName).ToArray();
}
nameLengthDif = res.Length
How about
private static int GetDifferenceCount(string firstName, string lastName)
{
int differences;
string longestString = firstName;
if (longestString.Length < lastName.Length)
longestString = lastName;
for (int i = 0; i < longestString.Length; i++)
{
try
{
if (firstName.Substring(i, 1) != lastName.Substring(i, 1))
differences++;
}
catch
differences++;
}
return differences;
}
To return number of different characters. You could then say
if (GetDifferenceCount(firstName, lastName) >= 2)
// Do something
Completing an action if 2 or more characters are different.