I’m a beginner in C# and I’m stuck at this problem.
string original = "foo bar foo $ bar $ foo bar $ ";
string desired_output = "foo bar foo $ bar foo bar";
I found a rough code but the result is not good.
can you help me solve the problem?
Here is my code:
string s = "foo bar foo $ bar $ foo bar $ ";
char ch = '$';
for (int i = 0; i < s.Length; i++)
{
if (s[i] == ch)
{
s = s.Substring(0, i) +
s.Substring(i + 1);
break;
}
}
for (int i = s.Length - 1; i > -1; i--)
{
if (s[i] == ch)
{
s = s.Substring(0, i) +
s.Substring(i + 1);
break;
}
}
Console.WriteLine(s);
The output I receive is foo bar foo bar $ foo bar.
>Solution :
string original = "foo bar foo $ bar $ foo bar $ ";
string desired_output = "foo bar foo $ bar foo bar";
string result = original;
int index = original.IndexOf("$")+1;
if (index > 0)
{
result = (original.Substring(0, index) + original.Substring(index).Replace("$", "")).Replace(" ", " ").Trim();
}
Console.WriteLine(desired_output == result);
See it here:
Or:
string original = "foo bar foo $ bar $ foo bar $ ";
string desired_output = "foo bar foo $ bar foo bar";
var buffer = original.ToCharArray();
bool found = false;
int dest = 0;
for(int i = 0; i < buffer.Length; i++)
{
if (buffer[i] != '$' || !found)
{
buffer[dest] = buffer[i];
dest++;
}
if (buffer[i] == '$') found = true;
}
var result = new string(buffer, 0, dest).Replace(" ", " ").Trim();
Console.WriteLine(desired_output == result);
Notice for both solutions there is an issue with the extra spacing, hence the extra Replace() and Trim() calls.