I want to replace the fifth space in a sentence with a new line. Sample input:
"Hi this is empty string. This should be in new line!"
Expected output:
"Hi this is empty string.
This should be in new line!"
I'm getting the expected output with this code, but I need to know, is this the optimized solution or there are any better solution than this?
string s = "Hi this is empty string. This should be in new line!", t = "";
int countSpaces = s.Count(Char.IsWhiteSpace);
if (countSpaces > 3)
{
int count = 0;
char n;
foreach (char c in s)
{
if (c == ' ') count++;
if (count == 5)
{
n = '\n';
count++;
}
else n = c;
t += n;
}
}
else t = s;
MessageBox.Show(t);