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
.
CodePudding user response:
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.
CodePudding user response:
If you want to keep only the first $ then the first thing you would need to do is use that first for loop to find the first $ and make the latter substring until the end of the main string. Once you've done that, use the Replace function to replace all other $ in that substring. Then just combine the first part of the substring and the cleaned second part and you will get your desired output
CodePudding user response:
You do not need 2 for loops for that. One is enough. Just copy all chars into a StringBuilder
, except, if the char is the desired character ($
) and it was already copied once before. A single bool flag suffices to accomplish that.
using System;
using System.Text;
namespace cs
{
class Program
{
static string RemoveAllButFirst(char c, string s) {
var first = true;
var sb = new StringBuilder();
foreach (char x in s) {
if (c == x) {
if (first) {
sb.Append(x);
first = false;
}
} else {
sb.Append(x);
}
}
return sb.ToString();
}
static void Main(string[] args)
{
string original = "foo bar foo $ bar $ foo bar $ ";
System.Console.WriteLine(original);
System.Console.WriteLine(RemoveAllButFirst( '$', original));
}
}
}