Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removes all but the first occurance of a given char in the string

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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:

https://dotnetfiddle.net/I3lVua


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);

https://dotnetfiddle.net/iVtw8E

Notice for both solutions there is an issue with the extra spacing, hence the extra Replace() and Trim() calls.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading