I take practice with my logical to improve, but I got lack with numbers of two for-loop, one for collect letters to store into array from the name, and another one for store each letters that request letters to convert lowercase to uppercase in the name.
Excuse me for my English is weak.
Example Console Application display:
Insert of your name:
john
Insert any the letter to convert to uppercase:
jn
Output: JohN
My code at below:
string name = "";
Console.WriteLine("Insert your name");
name = Console.ReadLine();
string letter = "";
Console.WriteLine("Insert of letter");
letter = Console.ReadLine();
char[] ch = name.ToCharArray();
string[] name2 = new string[name.Length];
char[] chletter = letter.ToCharArray();
string[] letterArray = new string[chletter.Length];
for (int i = 0; i < ch.Length; i ) //loop count of each letters from the names.
{
name2[i] = ch[i].ToString();// convert fullname into letters to store into string Name2
}
for (int i = 0; i < letterArray.Length; i )
{
letterArray[i] = chletter[i].ToString().ToUpper();
}
for (int i = 0; i < letterArray.Length; i )
{
if (name2[i].ToUpper() == letterArray[i]) // Find letter from name2 array when you ask for.
{
name2[i] = letterArray[i];
}
}
for (int i = 0; i < name2.Length; i )// display value from array
{
Console.Write(name2[i]);
}
CodePudding user response:
You should be able to do it in one loop without using indexes, which should eliminate your issue with invalid index
var name = Console.ReadLine().ToCharArray();
var lettersToChange = Console.ReadLine().ToCharArray().ToHashSet();
var builder = new StringBuilder();
foreach (var letter in name)
{
var newLetter = lettersToChange.Contains(letter)
? Char.ToUpper(letter)
: letter;
builder.Append(newLetter);
}
var result = builder.ToString();
CodePudding user response:
This sounds like a homework assignment, but anyway here are a few hints...
1- You create new arrays like this:
string[] letterArray = new string[chletter.Length];
but that's not actually the "value" of the chkletter string, that's just a new array with the same size (but no actual content)
2- The part (see 1) where you create an array of characters
char[] chletter = letter.ToCharArray();
is already the same array (but with actual content)
3- Why would you want to convert the single character to a string and to upper case EVERY time you run that loop?
letterArray[i] = chletter[i].ToString().ToUpper();
Wouldn't it be easier (and better for performance) if you'd only have to do that ONCE?
And last
4- If you already converted the strings to upper case, could you find a way to compare any of these characters in a single loop?
This not to be bitchy, but think about what you ask and what you attempt to achieve.