Prints each letter of a string in different colorsCounting the occurrence of each letter in a stringComparing...
Why are there five extra turns in tournament Magic?
Why does a table with a defined constant in its index compute 10X slower?
In Dutch history two people are referred to as "William III"; are there any more cases where this happens?
Can the Gate spell draw a creature larger that 20 feet in every dimension through the portal it creates?
Can I get the output of a command line program with TeX (using e.g. read18)?
Is it possible to determine from only a photo of a cityscape whether it was taken close with wide angle or from a distance with zoom?
How to get all possible paths in 0/1 matrix better way?
What technology would Dwarves need to forge titanium?
Good examples of "two is easy, three is hard" in computational sciences
on the truth quest vs in the quest for truth
Merging two rows with rounding their first elemnts
pwaS eht tirsf dna tasl setterl fo hace dorw
Is there any deeper thematic meaning to the white horse that Arya finds in The Bells (S08E05)?
Why does the setuid bit work inconsistently?
How to laser-level close to a surface
How to say "that" as in "the cow that ate" in Japanese?
Physically unpleasant work environment
What were the "pills" that were added to solid waste in Apollo 7?
Who is frowning in the sentence "Daisy looked at Tom frowning"?
Was murdering a slave illegal in American slavery, and if so, what punishments were given for it?
Why aren't satellites disintegrated even though they orbit earth within earth's Roche Limits?
Why use a retrograde orbit?
Why is so much ransomware breakable?
Are there any symmetric cryptosystems based on computational complexity assumptions?
Prints each letter of a string in different colors
Counting the occurrence of each letter in a stringComparing different string-matching functionsGenerating Unique ColorsFinding the maximum pairwise difference in a collection of colorsExtension method splitting string on each capital letterComparing XML string with different formatsIncrementing colorsGenerating an image with all 15-bit colors, each used exactly onceUpdate SQL database, similar-but-different queries for each monthReturn Full Month Name From 3 Letter Month
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}
$begingroup$
I'm practicing for my Technical Interview and I'm worried my code does not meet the bar. What can I do to improve this answer?
Here is the question: https://www.careercup.com/question?id=5739126414901248
Given
colors = ["red", "blue", "green", "yellow"];
and a string
str = "Lorem ipsum dolor sit amet";
write a function that prints each letter of the string in different colors. ex. L
is red, o
is blue, r
is green, e
is yellow, m
is red, after the space, i
should be blue.
My answer:
static void TestPrintColors()
{
string[] colors = new string[4] {"red", "blue", "green", "yellow"};
string str = "Lorem ipsum dolor sit amet";
PrintColors(colors, str);
}
static void PrintColors(string[] colors, string str)
{
char log;
ConsoleColor originalColor = Console.ForegroundColor;
int colorIndex = 0;
ConsoleColor currentColor = originalColor;
for (int i = 0; i < str.Length; i++)
{
log = str[i];
if (log == ' ')
{
Console.WriteLine(log);
continue;
}
switch(colors[colorIndex])
{
case "red":
currentColor = ConsoleColor.Red;
break;
case "blue":
currentColor = ConsoleColor.Blue;
break;
case "green":
currentColor = ConsoleColor.Green;
break;
case "yellow":
currentColor = ConsoleColor.Yellow;
break;
default:
currentColor = originalColor;
break;
}
colorIndex++;
if (colorIndex >= colors.Length)
{
colorIndex = 0;
}
Console.ForegroundColor = currentColor;
Console.WriteLine(log);
}
Console.ForegroundColor = originalColor;
}
c# performance
New contributor
$endgroup$
add a comment |
$begingroup$
I'm practicing for my Technical Interview and I'm worried my code does not meet the bar. What can I do to improve this answer?
Here is the question: https://www.careercup.com/question?id=5739126414901248
Given
colors = ["red", "blue", "green", "yellow"];
and a string
str = "Lorem ipsum dolor sit amet";
write a function that prints each letter of the string in different colors. ex. L
is red, o
is blue, r
is green, e
is yellow, m
is red, after the space, i
should be blue.
My answer:
static void TestPrintColors()
{
string[] colors = new string[4] {"red", "blue", "green", "yellow"};
string str = "Lorem ipsum dolor sit amet";
PrintColors(colors, str);
}
static void PrintColors(string[] colors, string str)
{
char log;
ConsoleColor originalColor = Console.ForegroundColor;
int colorIndex = 0;
ConsoleColor currentColor = originalColor;
for (int i = 0; i < str.Length; i++)
{
log = str[i];
if (log == ' ')
{
Console.WriteLine(log);
continue;
}
switch(colors[colorIndex])
{
case "red":
currentColor = ConsoleColor.Red;
break;
case "blue":
currentColor = ConsoleColor.Blue;
break;
case "green":
currentColor = ConsoleColor.Green;
break;
case "yellow":
currentColor = ConsoleColor.Yellow;
break;
default:
currentColor = originalColor;
break;
}
colorIndex++;
if (colorIndex >= colors.Length)
{
colorIndex = 0;
}
Console.ForegroundColor = currentColor;
Console.WriteLine(log);
}
Console.ForegroundColor = originalColor;
}
c# performance
New contributor
$endgroup$
$begingroup$
Have you tested the code? If you have tested the code could you please provide the code that calls this function?
$endgroup$
– pacmaninbw
7 hours ago
$begingroup$
@pacmaninbw The calling function isTestPrintColors()
. That in turn would be called from a Console Application'sMain
method.
$endgroup$
– benj2240
5 hours ago
add a comment |
$begingroup$
I'm practicing for my Technical Interview and I'm worried my code does not meet the bar. What can I do to improve this answer?
Here is the question: https://www.careercup.com/question?id=5739126414901248
Given
colors = ["red", "blue", "green", "yellow"];
and a string
str = "Lorem ipsum dolor sit amet";
write a function that prints each letter of the string in different colors. ex. L
is red, o
is blue, r
is green, e
is yellow, m
is red, after the space, i
should be blue.
My answer:
static void TestPrintColors()
{
string[] colors = new string[4] {"red", "blue", "green", "yellow"};
string str = "Lorem ipsum dolor sit amet";
PrintColors(colors, str);
}
static void PrintColors(string[] colors, string str)
{
char log;
ConsoleColor originalColor = Console.ForegroundColor;
int colorIndex = 0;
ConsoleColor currentColor = originalColor;
for (int i = 0; i < str.Length; i++)
{
log = str[i];
if (log == ' ')
{
Console.WriteLine(log);
continue;
}
switch(colors[colorIndex])
{
case "red":
currentColor = ConsoleColor.Red;
break;
case "blue":
currentColor = ConsoleColor.Blue;
break;
case "green":
currentColor = ConsoleColor.Green;
break;
case "yellow":
currentColor = ConsoleColor.Yellow;
break;
default:
currentColor = originalColor;
break;
}
colorIndex++;
if (colorIndex >= colors.Length)
{
colorIndex = 0;
}
Console.ForegroundColor = currentColor;
Console.WriteLine(log);
}
Console.ForegroundColor = originalColor;
}
c# performance
New contributor
$endgroup$
I'm practicing for my Technical Interview and I'm worried my code does not meet the bar. What can I do to improve this answer?
Here is the question: https://www.careercup.com/question?id=5739126414901248
Given
colors = ["red", "blue", "green", "yellow"];
and a string
str = "Lorem ipsum dolor sit amet";
write a function that prints each letter of the string in different colors. ex. L
is red, o
is blue, r
is green, e
is yellow, m
is red, after the space, i
should be blue.
My answer:
static void TestPrintColors()
{
string[] colors = new string[4] {"red", "blue", "green", "yellow"};
string str = "Lorem ipsum dolor sit amet";
PrintColors(colors, str);
}
static void PrintColors(string[] colors, string str)
{
char log;
ConsoleColor originalColor = Console.ForegroundColor;
int colorIndex = 0;
ConsoleColor currentColor = originalColor;
for (int i = 0; i < str.Length; i++)
{
log = str[i];
if (log == ' ')
{
Console.WriteLine(log);
continue;
}
switch(colors[colorIndex])
{
case "red":
currentColor = ConsoleColor.Red;
break;
case "blue":
currentColor = ConsoleColor.Blue;
break;
case "green":
currentColor = ConsoleColor.Green;
break;
case "yellow":
currentColor = ConsoleColor.Yellow;
break;
default:
currentColor = originalColor;
break;
}
colorIndex++;
if (colorIndex >= colors.Length)
{
colorIndex = 0;
}
Console.ForegroundColor = currentColor;
Console.WriteLine(log);
}
Console.ForegroundColor = originalColor;
}
c# performance
c# performance
New contributor
New contributor
edited 17 mins ago
t3chb0t
35.8k756129
35.8k756129
New contributor
asked 10 hours ago
Austin TaylorAustin Taylor
434
434
New contributor
New contributor
$begingroup$
Have you tested the code? If you have tested the code could you please provide the code that calls this function?
$endgroup$
– pacmaninbw
7 hours ago
$begingroup$
@pacmaninbw The calling function isTestPrintColors()
. That in turn would be called from a Console Application'sMain
method.
$endgroup$
– benj2240
5 hours ago
add a comment |
$begingroup$
Have you tested the code? If you have tested the code could you please provide the code that calls this function?
$endgroup$
– pacmaninbw
7 hours ago
$begingroup$
@pacmaninbw The calling function isTestPrintColors()
. That in turn would be called from a Console Application'sMain
method.
$endgroup$
– benj2240
5 hours ago
$begingroup$
Have you tested the code? If you have tested the code could you please provide the code that calls this function?
$endgroup$
– pacmaninbw
7 hours ago
$begingroup$
Have you tested the code? If you have tested the code could you please provide the code that calls this function?
$endgroup$
– pacmaninbw
7 hours ago
$begingroup$
@pacmaninbw The calling function is
TestPrintColors()
. That in turn would be called from a Console Application's Main
method.$endgroup$
– benj2240
5 hours ago
$begingroup$
@pacmaninbw The calling function is
TestPrintColors()
. That in turn would be called from a Console Application's Main
method.$endgroup$
– benj2240
5 hours ago
add a comment |
2 Answers
2
active
oldest
votes
$begingroup$
Don't worry about performance.
You're writing a handful of strings to the console, and it takes milliseconds. When you start writing tens of thousands of strings, and notice it taking seconds, then you can you start to look for optimizations. Until then, the cleanliness of your code is much more important.
Your function is too long.
This is a fifty-line function. It has the responsibilities of iterating through two lists in parallel, skipping spaces, parsing color names, setting the console color, writing to console, and resetting the console color when it's all done. That's a lot! Break it up into smaller functions.
Switch statements are ugly.
I don't mean that they are never appropriate, but ConsoleColor
is an enum
, and it's possible to parse enums (while ignoring case sensitivity). You should replace this switch statement with a function call.
Don't initialize variables until you need them.
With few exceptions, modern languages are very good about optimizing variable allocation. Putting char log = str[i]
inside the loop will not result in additional memory usage, and it will save me (a potential reviewer or maintenance programmer) from having to think about that character before or after the loop.
Other tips...
You say this is practice for an interview, so it could be a good place for you to show off your knowledge of C#. With a little trouble, you could leverage Regular Expressions and LINQ to save you from manually manipulating array indexes. With a little more trouble, you could leverage IDisposable to ensure the original ForegroundColor is restored when all is said and done.
On the other hand, you could also shoot yourself in the foot attempting to do those things. If you don't honestly have in-depth knowledge about C#, it might be best just to aim for code that is as simple as possible. I think the best way to do that is to make small functions with clear names, to show you are thinking about the maintainability and reusability of your code.
$endgroup$
1
$begingroup$
Nicely said! Thank you for the great response! I would like to update my code and get feedback, what is the best way to do that? Sorry I'm, new here. Thank you!
$endgroup$
– Austin Taylor
7 hours ago
1
$begingroup$
Welcome to CodeReview! The usual rule is that you may make edits to your code until the first answer is posted. At this point, if you were to edit this question my answer would look silly. Please, feel free to post a follow-up question with your updated code, maybe linking back to this one for reference.
$endgroup$
– benj2240
7 hours ago
add a comment |
$begingroup$
Declaring array size
Since you're declaring and initializing the array in one step, you don't need to declare the array size. Omitting the array size means you can add/remove elements from the initialization without needing to worry about also changing the number in the declaration.
// before
string[] colors = new string[4] {"red", "blue", "green", "yellow"};
// after
string[] colors = new string[] {"red", "blue", "green", "yellow"};
Circular looping
You can make this a neat one-liner using the modulus operator (or if you want your code to be ugly, a ternary operator). It's personal preference but the modulus operator has the added benefit of allowing you to iterate backwards because it will wrap your index/iterator even if it goes negative.
// before
colorIndex++;
if (colorIndex >= colors.Length)
{
colorIndex = 0;
}
// after
colorIndex = (colorIndex + 1) % colors.Length;
For loop
You use a for loop to iterate your string, but the iterator/index variable i
is only used to retrieve the char element from the appropriate position. Since the rest of your code isn't dependent on the numerical index value, you can just use a foreach loop. Remember to remove the declaration for the log variable if you declare it in your foreach loop.
// before
for (int i = 0; i < str.Length; i++)
{
log = str[i];
// after
foreach (char log in str)
{
Checking for white space
C#'s char primitive type has a built-in check for white space which covers more than just spacebar.
// before
if (log == ' ')
// after
if (char.IsWhiteSpace(log))
Switch statements
As mentioned by another answer, switch statements are ugly. But there's another reason to opt for a different solution: if you want to add more colors to your array, you will also need to remember to add more cases to the switch statement.
// before
switch (colors[colorIndex])
{
case "red":
currentColor = ConsoleColor.Red;
break;
case "blue":
currentColor = ConsoleColor.Blue;
break;
case "green":
currentColor = ConsoleColor.Green;
break;
case "yellow":
currentColor = ConsoleColor.Yellow;
break;
default:
currentColor = originalColor;
break;
}
// after
if (!Enum.TryParse(colors[colorIndex], true, out currentColor))
{
currentColor = originalColor;
}
The adjustments I pointed out result in significantly less code that is more maintainable. It is functionally the same, and flexible in that you can easily add more colors later if you wanted to by just adding them to your array initialization.
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Austin Taylor is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f220371%2fprints-each-letter-of-a-string-in-different-colors%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
Don't worry about performance.
You're writing a handful of strings to the console, and it takes milliseconds. When you start writing tens of thousands of strings, and notice it taking seconds, then you can you start to look for optimizations. Until then, the cleanliness of your code is much more important.
Your function is too long.
This is a fifty-line function. It has the responsibilities of iterating through two lists in parallel, skipping spaces, parsing color names, setting the console color, writing to console, and resetting the console color when it's all done. That's a lot! Break it up into smaller functions.
Switch statements are ugly.
I don't mean that they are never appropriate, but ConsoleColor
is an enum
, and it's possible to parse enums (while ignoring case sensitivity). You should replace this switch statement with a function call.
Don't initialize variables until you need them.
With few exceptions, modern languages are very good about optimizing variable allocation. Putting char log = str[i]
inside the loop will not result in additional memory usage, and it will save me (a potential reviewer or maintenance programmer) from having to think about that character before or after the loop.
Other tips...
You say this is practice for an interview, so it could be a good place for you to show off your knowledge of C#. With a little trouble, you could leverage Regular Expressions and LINQ to save you from manually manipulating array indexes. With a little more trouble, you could leverage IDisposable to ensure the original ForegroundColor is restored when all is said and done.
On the other hand, you could also shoot yourself in the foot attempting to do those things. If you don't honestly have in-depth knowledge about C#, it might be best just to aim for code that is as simple as possible. I think the best way to do that is to make small functions with clear names, to show you are thinking about the maintainability and reusability of your code.
$endgroup$
1
$begingroup$
Nicely said! Thank you for the great response! I would like to update my code and get feedback, what is the best way to do that? Sorry I'm, new here. Thank you!
$endgroup$
– Austin Taylor
7 hours ago
1
$begingroup$
Welcome to CodeReview! The usual rule is that you may make edits to your code until the first answer is posted. At this point, if you were to edit this question my answer would look silly. Please, feel free to post a follow-up question with your updated code, maybe linking back to this one for reference.
$endgroup$
– benj2240
7 hours ago
add a comment |
$begingroup$
Don't worry about performance.
You're writing a handful of strings to the console, and it takes milliseconds. When you start writing tens of thousands of strings, and notice it taking seconds, then you can you start to look for optimizations. Until then, the cleanliness of your code is much more important.
Your function is too long.
This is a fifty-line function. It has the responsibilities of iterating through two lists in parallel, skipping spaces, parsing color names, setting the console color, writing to console, and resetting the console color when it's all done. That's a lot! Break it up into smaller functions.
Switch statements are ugly.
I don't mean that they are never appropriate, but ConsoleColor
is an enum
, and it's possible to parse enums (while ignoring case sensitivity). You should replace this switch statement with a function call.
Don't initialize variables until you need them.
With few exceptions, modern languages are very good about optimizing variable allocation. Putting char log = str[i]
inside the loop will not result in additional memory usage, and it will save me (a potential reviewer or maintenance programmer) from having to think about that character before or after the loop.
Other tips...
You say this is practice for an interview, so it could be a good place for you to show off your knowledge of C#. With a little trouble, you could leverage Regular Expressions and LINQ to save you from manually manipulating array indexes. With a little more trouble, you could leverage IDisposable to ensure the original ForegroundColor is restored when all is said and done.
On the other hand, you could also shoot yourself in the foot attempting to do those things. If you don't honestly have in-depth knowledge about C#, it might be best just to aim for code that is as simple as possible. I think the best way to do that is to make small functions with clear names, to show you are thinking about the maintainability and reusability of your code.
$endgroup$
1
$begingroup$
Nicely said! Thank you for the great response! I would like to update my code and get feedback, what is the best way to do that? Sorry I'm, new here. Thank you!
$endgroup$
– Austin Taylor
7 hours ago
1
$begingroup$
Welcome to CodeReview! The usual rule is that you may make edits to your code until the first answer is posted. At this point, if you were to edit this question my answer would look silly. Please, feel free to post a follow-up question with your updated code, maybe linking back to this one for reference.
$endgroup$
– benj2240
7 hours ago
add a comment |
$begingroup$
Don't worry about performance.
You're writing a handful of strings to the console, and it takes milliseconds. When you start writing tens of thousands of strings, and notice it taking seconds, then you can you start to look for optimizations. Until then, the cleanliness of your code is much more important.
Your function is too long.
This is a fifty-line function. It has the responsibilities of iterating through two lists in parallel, skipping spaces, parsing color names, setting the console color, writing to console, and resetting the console color when it's all done. That's a lot! Break it up into smaller functions.
Switch statements are ugly.
I don't mean that they are never appropriate, but ConsoleColor
is an enum
, and it's possible to parse enums (while ignoring case sensitivity). You should replace this switch statement with a function call.
Don't initialize variables until you need them.
With few exceptions, modern languages are very good about optimizing variable allocation. Putting char log = str[i]
inside the loop will not result in additional memory usage, and it will save me (a potential reviewer or maintenance programmer) from having to think about that character before or after the loop.
Other tips...
You say this is practice for an interview, so it could be a good place for you to show off your knowledge of C#. With a little trouble, you could leverage Regular Expressions and LINQ to save you from manually manipulating array indexes. With a little more trouble, you could leverage IDisposable to ensure the original ForegroundColor is restored when all is said and done.
On the other hand, you could also shoot yourself in the foot attempting to do those things. If you don't honestly have in-depth knowledge about C#, it might be best just to aim for code that is as simple as possible. I think the best way to do that is to make small functions with clear names, to show you are thinking about the maintainability and reusability of your code.
$endgroup$
Don't worry about performance.
You're writing a handful of strings to the console, and it takes milliseconds. When you start writing tens of thousands of strings, and notice it taking seconds, then you can you start to look for optimizations. Until then, the cleanliness of your code is much more important.
Your function is too long.
This is a fifty-line function. It has the responsibilities of iterating through two lists in parallel, skipping spaces, parsing color names, setting the console color, writing to console, and resetting the console color when it's all done. That's a lot! Break it up into smaller functions.
Switch statements are ugly.
I don't mean that they are never appropriate, but ConsoleColor
is an enum
, and it's possible to parse enums (while ignoring case sensitivity). You should replace this switch statement with a function call.
Don't initialize variables until you need them.
With few exceptions, modern languages are very good about optimizing variable allocation. Putting char log = str[i]
inside the loop will not result in additional memory usage, and it will save me (a potential reviewer or maintenance programmer) from having to think about that character before or after the loop.
Other tips...
You say this is practice for an interview, so it could be a good place for you to show off your knowledge of C#. With a little trouble, you could leverage Regular Expressions and LINQ to save you from manually manipulating array indexes. With a little more trouble, you could leverage IDisposable to ensure the original ForegroundColor is restored when all is said and done.
On the other hand, you could also shoot yourself in the foot attempting to do those things. If you don't honestly have in-depth knowledge about C#, it might be best just to aim for code that is as simple as possible. I think the best way to do that is to make small functions with clear names, to show you are thinking about the maintainability and reusability of your code.
answered 8 hours ago
benj2240benj2240
81618
81618
1
$begingroup$
Nicely said! Thank you for the great response! I would like to update my code and get feedback, what is the best way to do that? Sorry I'm, new here. Thank you!
$endgroup$
– Austin Taylor
7 hours ago
1
$begingroup$
Welcome to CodeReview! The usual rule is that you may make edits to your code until the first answer is posted. At this point, if you were to edit this question my answer would look silly. Please, feel free to post a follow-up question with your updated code, maybe linking back to this one for reference.
$endgroup$
– benj2240
7 hours ago
add a comment |
1
$begingroup$
Nicely said! Thank you for the great response! I would like to update my code and get feedback, what is the best way to do that? Sorry I'm, new here. Thank you!
$endgroup$
– Austin Taylor
7 hours ago
1
$begingroup$
Welcome to CodeReview! The usual rule is that you may make edits to your code until the first answer is posted. At this point, if you were to edit this question my answer would look silly. Please, feel free to post a follow-up question with your updated code, maybe linking back to this one for reference.
$endgroup$
– benj2240
7 hours ago
1
1
$begingroup$
Nicely said! Thank you for the great response! I would like to update my code and get feedback, what is the best way to do that? Sorry I'm, new here. Thank you!
$endgroup$
– Austin Taylor
7 hours ago
$begingroup$
Nicely said! Thank you for the great response! I would like to update my code and get feedback, what is the best way to do that? Sorry I'm, new here. Thank you!
$endgroup$
– Austin Taylor
7 hours ago
1
1
$begingroup$
Welcome to CodeReview! The usual rule is that you may make edits to your code until the first answer is posted. At this point, if you were to edit this question my answer would look silly. Please, feel free to post a follow-up question with your updated code, maybe linking back to this one for reference.
$endgroup$
– benj2240
7 hours ago
$begingroup$
Welcome to CodeReview! The usual rule is that you may make edits to your code until the first answer is posted. At this point, if you were to edit this question my answer would look silly. Please, feel free to post a follow-up question with your updated code, maybe linking back to this one for reference.
$endgroup$
– benj2240
7 hours ago
add a comment |
$begingroup$
Declaring array size
Since you're declaring and initializing the array in one step, you don't need to declare the array size. Omitting the array size means you can add/remove elements from the initialization without needing to worry about also changing the number in the declaration.
// before
string[] colors = new string[4] {"red", "blue", "green", "yellow"};
// after
string[] colors = new string[] {"red", "blue", "green", "yellow"};
Circular looping
You can make this a neat one-liner using the modulus operator (or if you want your code to be ugly, a ternary operator). It's personal preference but the modulus operator has the added benefit of allowing you to iterate backwards because it will wrap your index/iterator even if it goes negative.
// before
colorIndex++;
if (colorIndex >= colors.Length)
{
colorIndex = 0;
}
// after
colorIndex = (colorIndex + 1) % colors.Length;
For loop
You use a for loop to iterate your string, but the iterator/index variable i
is only used to retrieve the char element from the appropriate position. Since the rest of your code isn't dependent on the numerical index value, you can just use a foreach loop. Remember to remove the declaration for the log variable if you declare it in your foreach loop.
// before
for (int i = 0; i < str.Length; i++)
{
log = str[i];
// after
foreach (char log in str)
{
Checking for white space
C#'s char primitive type has a built-in check for white space which covers more than just spacebar.
// before
if (log == ' ')
// after
if (char.IsWhiteSpace(log))
Switch statements
As mentioned by another answer, switch statements are ugly. But there's another reason to opt for a different solution: if you want to add more colors to your array, you will also need to remember to add more cases to the switch statement.
// before
switch (colors[colorIndex])
{
case "red":
currentColor = ConsoleColor.Red;
break;
case "blue":
currentColor = ConsoleColor.Blue;
break;
case "green":
currentColor = ConsoleColor.Green;
break;
case "yellow":
currentColor = ConsoleColor.Yellow;
break;
default:
currentColor = originalColor;
break;
}
// after
if (!Enum.TryParse(colors[colorIndex], true, out currentColor))
{
currentColor = originalColor;
}
The adjustments I pointed out result in significantly less code that is more maintainable. It is functionally the same, and flexible in that you can easily add more colors later if you wanted to by just adding them to your array initialization.
$endgroup$
add a comment |
$begingroup$
Declaring array size
Since you're declaring and initializing the array in one step, you don't need to declare the array size. Omitting the array size means you can add/remove elements from the initialization without needing to worry about also changing the number in the declaration.
// before
string[] colors = new string[4] {"red", "blue", "green", "yellow"};
// after
string[] colors = new string[] {"red", "blue", "green", "yellow"};
Circular looping
You can make this a neat one-liner using the modulus operator (or if you want your code to be ugly, a ternary operator). It's personal preference but the modulus operator has the added benefit of allowing you to iterate backwards because it will wrap your index/iterator even if it goes negative.
// before
colorIndex++;
if (colorIndex >= colors.Length)
{
colorIndex = 0;
}
// after
colorIndex = (colorIndex + 1) % colors.Length;
For loop
You use a for loop to iterate your string, but the iterator/index variable i
is only used to retrieve the char element from the appropriate position. Since the rest of your code isn't dependent on the numerical index value, you can just use a foreach loop. Remember to remove the declaration for the log variable if you declare it in your foreach loop.
// before
for (int i = 0; i < str.Length; i++)
{
log = str[i];
// after
foreach (char log in str)
{
Checking for white space
C#'s char primitive type has a built-in check for white space which covers more than just spacebar.
// before
if (log == ' ')
// after
if (char.IsWhiteSpace(log))
Switch statements
As mentioned by another answer, switch statements are ugly. But there's another reason to opt for a different solution: if you want to add more colors to your array, you will also need to remember to add more cases to the switch statement.
// before
switch (colors[colorIndex])
{
case "red":
currentColor = ConsoleColor.Red;
break;
case "blue":
currentColor = ConsoleColor.Blue;
break;
case "green":
currentColor = ConsoleColor.Green;
break;
case "yellow":
currentColor = ConsoleColor.Yellow;
break;
default:
currentColor = originalColor;
break;
}
// after
if (!Enum.TryParse(colors[colorIndex], true, out currentColor))
{
currentColor = originalColor;
}
The adjustments I pointed out result in significantly less code that is more maintainable. It is functionally the same, and flexible in that you can easily add more colors later if you wanted to by just adding them to your array initialization.
$endgroup$
add a comment |
$begingroup$
Declaring array size
Since you're declaring and initializing the array in one step, you don't need to declare the array size. Omitting the array size means you can add/remove elements from the initialization without needing to worry about also changing the number in the declaration.
// before
string[] colors = new string[4] {"red", "blue", "green", "yellow"};
// after
string[] colors = new string[] {"red", "blue", "green", "yellow"};
Circular looping
You can make this a neat one-liner using the modulus operator (or if you want your code to be ugly, a ternary operator). It's personal preference but the modulus operator has the added benefit of allowing you to iterate backwards because it will wrap your index/iterator even if it goes negative.
// before
colorIndex++;
if (colorIndex >= colors.Length)
{
colorIndex = 0;
}
// after
colorIndex = (colorIndex + 1) % colors.Length;
For loop
You use a for loop to iterate your string, but the iterator/index variable i
is only used to retrieve the char element from the appropriate position. Since the rest of your code isn't dependent on the numerical index value, you can just use a foreach loop. Remember to remove the declaration for the log variable if you declare it in your foreach loop.
// before
for (int i = 0; i < str.Length; i++)
{
log = str[i];
// after
foreach (char log in str)
{
Checking for white space
C#'s char primitive type has a built-in check for white space which covers more than just spacebar.
// before
if (log == ' ')
// after
if (char.IsWhiteSpace(log))
Switch statements
As mentioned by another answer, switch statements are ugly. But there's another reason to opt for a different solution: if you want to add more colors to your array, you will also need to remember to add more cases to the switch statement.
// before
switch (colors[colorIndex])
{
case "red":
currentColor = ConsoleColor.Red;
break;
case "blue":
currentColor = ConsoleColor.Blue;
break;
case "green":
currentColor = ConsoleColor.Green;
break;
case "yellow":
currentColor = ConsoleColor.Yellow;
break;
default:
currentColor = originalColor;
break;
}
// after
if (!Enum.TryParse(colors[colorIndex], true, out currentColor))
{
currentColor = originalColor;
}
The adjustments I pointed out result in significantly less code that is more maintainable. It is functionally the same, and flexible in that you can easily add more colors later if you wanted to by just adding them to your array initialization.
$endgroup$
Declaring array size
Since you're declaring and initializing the array in one step, you don't need to declare the array size. Omitting the array size means you can add/remove elements from the initialization without needing to worry about also changing the number in the declaration.
// before
string[] colors = new string[4] {"red", "blue", "green", "yellow"};
// after
string[] colors = new string[] {"red", "blue", "green", "yellow"};
Circular looping
You can make this a neat one-liner using the modulus operator (or if you want your code to be ugly, a ternary operator). It's personal preference but the modulus operator has the added benefit of allowing you to iterate backwards because it will wrap your index/iterator even if it goes negative.
// before
colorIndex++;
if (colorIndex >= colors.Length)
{
colorIndex = 0;
}
// after
colorIndex = (colorIndex + 1) % colors.Length;
For loop
You use a for loop to iterate your string, but the iterator/index variable i
is only used to retrieve the char element from the appropriate position. Since the rest of your code isn't dependent on the numerical index value, you can just use a foreach loop. Remember to remove the declaration for the log variable if you declare it in your foreach loop.
// before
for (int i = 0; i < str.Length; i++)
{
log = str[i];
// after
foreach (char log in str)
{
Checking for white space
C#'s char primitive type has a built-in check for white space which covers more than just spacebar.
// before
if (log == ' ')
// after
if (char.IsWhiteSpace(log))
Switch statements
As mentioned by another answer, switch statements are ugly. But there's another reason to opt for a different solution: if you want to add more colors to your array, you will also need to remember to add more cases to the switch statement.
// before
switch (colors[colorIndex])
{
case "red":
currentColor = ConsoleColor.Red;
break;
case "blue":
currentColor = ConsoleColor.Blue;
break;
case "green":
currentColor = ConsoleColor.Green;
break;
case "yellow":
currentColor = ConsoleColor.Yellow;
break;
default:
currentColor = originalColor;
break;
}
// after
if (!Enum.TryParse(colors[colorIndex], true, out currentColor))
{
currentColor = originalColor;
}
The adjustments I pointed out result in significantly less code that is more maintainable. It is functionally the same, and flexible in that you can easily add more colors later if you wanted to by just adding them to your array initialization.
edited 5 hours ago
answered 5 hours ago
rshepprshepp
1485
1485
add a comment |
add a comment |
Austin Taylor is a new contributor. Be nice, and check out our Code of Conduct.
Austin Taylor is a new contributor. Be nice, and check out our Code of Conduct.
Austin Taylor is a new contributor. Be nice, and check out our Code of Conduct.
Austin Taylor is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f220371%2fprints-each-letter-of-a-string-in-different-colors%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
$begingroup$
Have you tested the code? If you have tested the code could you please provide the code that calls this function?
$endgroup$
– pacmaninbw
7 hours ago
$begingroup$
@pacmaninbw The calling function is
TestPrintColors()
. That in turn would be called from a Console Application'sMain
method.$endgroup$
– benj2240
5 hours ago