Can't get my method to upper case my string arrays - c#

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)

Related

Reversed chars - foreach loop

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());
}

How can i get index of two same character in string?

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

English to Pig Latin C# Console Application

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 :)

Algorithm to find the three longest unique palindromes in a string

Using C#, write an algorithm to find the three longest unique palindromes in a string. For the three longest palindromes, report the palindrome text, start index and length in descending order of length. For example, the output for string,
sqrrqabccbatudefggfedvwhijkllkjihxymnnmzpop
should be:
Text: hijkllkjih, Index: 23, Length: 10 Text: defggfed, Index: 13, Length: 8 Text: abccba, Index: 5 Length: 6
Now I got to the part where I can write out the palindromes and its length but I have a problem with the index. Need help on how to include the index of the palindrome and how to get unique lengths
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string inputString = "sqrrqabccbatudefggfedvwhijkllkjihxymnnmzpop";
string currentStr = string.Empty;
List<string> listOfPalindromes = new List<string>();
char[] inputStrArr = inputString.ToCharArray();
for (int i = 0; i < inputStrArr.Length; i++)
{
for (int j = i+1; j < inputStrArr.Length; j++)
{
currentStr = inputString.Substring(i, j - i + 1);
if (IsPalindrome(currentStr))
{
listOfPalindromes.Add(currentStr);
}
}
}
var longest = (from str in listOfPalindromes
orderby str.Length descending
select str).Take(3);
foreach (var item in longest)
{
Console.WriteLine("Text: " + item.ToString() + " Index: " + + " Length: " + item.Length.ToString());
}
}
private static bool IsPalindrome(String str)
{
bool IsPalindrome = true;
if (str.Length > 0)
{
for (int i = 0; i < str.Length / 2; i++)
{
if (str.Substring(i, 1) != str.Substring(str.Length - (i + 1), 1))
{
IsPalindrome = false;
}
}
}
else
{
IsPalindrome = false;
}
return IsPalindrome;
}
}
}
ok now that's out of the way how do I get distinct lengths? can it be done by using DISTINCT or do I need to edit something else?
You need to store more information when a palindrome is found.
First define a class:
class PalindromeResult
{
public string Text { get; set; }
public int Index { get; set; }
}
Then instead of your List<string>, create a list of this class:
List<PalindromeResult> listOfPalindromes = new List<PalindromeResult>();
When a result is found, ad it like this
if (IsPalindrome(currentStr))
{
listOfPalindromes.Add(new PalindromeResult { Text = currentStr, Index = i});
}
You would have to update your sorting and printing accordingly.
The most optimal solution (as pointed out by Sinatr) would be to store the index of the palindromes as you find them.
You could instead use the IndexOf function to find the index of the first occurrence of a substring within a string.
For example inputString.IndexOf(item) could be used in your Console.WriteLine function.
Try This
public static bool IsPalindromic(int l)
{
IEnumerable<char> forwards = l.ToString().ToCharArray();
return forwards.SequenceEqual(forwards.Reverse());
}
public int LongestPalindrome(List<int> integers)
{
int length=0;
int num;
foreach (var integer in integers)
{
if (integer.ToString().Length > length)
{
num = integer;
length = integer.ToString().Length;
}
}
return num;
}
public void MyFunction(string input)
{
var numbers = Regex.Split(input, #"\D+").ToList();
var allPalindromes = (from value in numbers where !string.IsNullOrEmpty(value) select int.Parse(value) into i where IsPalindromic(i) select i).ToList();
if (allPalindromes.Count>0)
Console.WriteLine(LongestPalindrome(allPalindromes));
else
Console.WriteLine("Any Palindrome number was found");
}
you cans mix the 2 two functions to have a beautiful code but i done it like this to simplify.

C# pass gen recursion

I have a password generator that uses the ascii table. I am trying to learn how to use the recursion with it. I know there are easy ways to make a generator but I want to learn more about recursion. I want it to choose the letters (65-90) but also choose the numbers (000 - 009)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class PasswordGenerator
{
static void Main()
{
bool bypass = false;
string errorMessage = "That is an Invalid Number, Please try again";
string howManyCharacters = "How many Characters would you like the Password to be? (Press '0' to Stop)";
string pressKeyMessage = "Press any key to continue";
int length = 0;
do
{
var passwordBuilder = new StringBuilder();
Console.WriteLine(howManyCharacters);
var inputIsNumber = int.TryParse(Console.ReadLine(), out length);
if (!inputIsNumber)
{
Console.WriteLine(errorMessage);
bypass = false;
}
else if (inputIsNumber && length != 0)
{
for (int i = 0; i < length; i++)
passwordBuilder.Append(GetRandomChar());
Console.WriteLine();
Console.WriteLine("Password: " + passwordBuilder.ToString());
Console.WriteLine();
}
else
{
Console.WriteLine();
Console.WriteLine(pressKeyMessage);
Console.ReadLine();
bypass = true;
}
}
while (!bypass);
}
static Random _r = new Random();
static char GetRandomChar()
{
return (char)_r.Next(65, 90); // A through Z
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class PasswordGenerator
{
static void Main()
{
bool bypass = false;
int length = 0;
do
{
var passwordBuilder = new StringBuilder();
Console.WriteLine("How many Characters would you like the Password to be? (Press '-1' to Stop)");
/// try method is inside, replaced old try and catch
var Input_is_Int = int.TryParse(Console.ReadLine(), out length);
if (!Input_is_Int || length == 0)
{
Console.WriteLine("That is an Invalid Number, Please try again");
Console.WriteLine();
bypass = false;
}
else if (Input_is_Int && length != -1)
{
for (int i = 0; i < length; i++)
passwordBuilder.Append(GetRandomChar());
Console.WriteLine("Password: " + passwordBuilder.ToString());
Console.WriteLine();
}
else
{
Console.WriteLine();
Console.WriteLine("Press any key to continue");
Console.ReadLine();
bypass = true;
}
}
while (!bypass);
}
/// Union of ABCDEFGHIJKLMNOPQRSTUVWXYZ, 0123456789 and !"#$%&'()*+,-./
static char[] _lookupTable = Enumerable.Range(65, 26).Union(Enumerable.Range(48, 10).Union(Enumerable.Range(33, 14))).Select(i => (char)i).ToArray();
static Random _r = new Random();
static char GetRandomChar()
{
var index = _r.Next(0, _lookupTable.Length);
return _lookupTable[index];
}
}

Categories

Resources