Remove Extra Space in String - C#

Shervan360 1,641 Reputation points
2022-10-16T15:51:43.893+00:00

Hello,

I have a CSV file as below:

250828-screenshot-2022-10-16-084510.png

In the last row, I have \t\t instead of space. I wrote a method (RemoveWhiteSpaceInString) but I cannot detect extra space. Is there any differences between ' ' and \t?

using System.Reflection;  
using System.Text;  
  
namespace ConsoleApp2  
{  
    internal class Program  
    {  
        static string RemoveWhiteSpaceInString(string pattern)  
        {  
            int count = 0;  
            StringBuilder SB = new StringBuilder();  
            bool PrevChar = false;  
            foreach (char item in pattern)  
            {  
                bool NextChar = item == ' ';  
                if (!NextChar || !PrevChar)  
                {  
                    SB.Append(item);  
                    PrevChar = NextChar;  
                }  
            }  
            return SB.ToString();  
        }  
        static void Main(string[] args)  
        {  
            string dirPath = Assembly.GetExecutingAssembly().Location;  
            DirectoryInfo dirInfo = new(dirPath);  
            while (!(dirInfo.Name == "bin"))  
            {  
                if (dirInfo.Parent == null) throw new Exception("fge");  
                dirInfo = dirInfo.Parent;  
            }  
            dirInfo = dirInfo.Parent;  
            string DataPath = Path.Combine(dirInfo.FullName, "Data");  
            DataPath = Path.Combine(DataPath, "Order.csv");  
  
            StreamReader mainFile = new(DataPath);  
            mainFile.ReadLine();  
  
            while (!mainFile.EndOfStream)  
            {  
                string[] fields = mainFile.ReadLine().Split(',', StringSplitOptions.TrimEntries);  
                foreach (string item in fields)  
                {  
                    Console.Write($"{RemoveWhiteSpaceInString(item),-20}");  
                }  
                Console.WriteLine();  
            }  
        }  
    }  
}  
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,168 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,461 Reputation points
    2022-10-16T16:15:03.817+00:00

    Try the following done in a console project but will work with any project type.

    using System.Text.RegularExpressions;  
      
    namespace ConsoleApp1  
    {  
        internal class Program  
        {  
            static void Main(string[] args)  
            {  
                string data = "Hello    World  nice to be   here   \t\t";  
                Console.WriteLine($"{data.Replace("\t", "").RemoveExtraSpaces()}...");  
                Console.ReadLine();  
            }  
        }  
      
        public static class Extensions  
        {  
            public static string RemoveExtraSpaces(this string sender)  
            {  
                const RegexOptions options = RegexOptions.None;  
                var regex = new Regex("[ ]{2,}", options);  
                return regex.Replace(sender, " ").Trim();  
            }  
        }  
    }  
    
    1 person found this answer helpful.
    0 comments No comments

  2. WayneAKing 4,926 Reputation points
    2022-10-17T01:05:00.027+00:00

    Is there any differences between ' ' and \t?

    Yes, they are two different characters.

    Perhaps the easiest way to make your method work is to
    replace all tabs with spaces before parsing the string.

    static string RemoveWhiteSpaceInString(string pattern)  
    {  
        string tempstr = pattern.Replace('\t', ' ');  
      
        int count = 0;  
        StringBuilder SB = new StringBuilder();  
        bool PrevChar = false;  
        foreach (char item in tempstr)  
            {  
            bool NextChar = item == ' ';  
            if (!NextChar || !PrevChar)  
            {  
                SB.Append(item);  
                PrevChar = NextChar;  
            }  
        }  
        return SB.ToString();  
    }  
      
    static void Main(string[] args)                                    
    {                                                                  
        string str = "HasSpacesAfter    after";                        
        string strTAB = "HasTabsAfter\t\tafter";                       
        string strTABandSpaces = "HasWhitespacesAfter  \t\t  after";   
                                                                       
                                                                       
        Console.WriteLine(str);                                        
        Console.WriteLine(strTAB);                                     
        Console.WriteLine(strTABandSpaces);                            
                                                                       
        Console.WriteLine(RemoveWhiteSpaceInString(str));              
        Console.WriteLine(RemoveWhiteSpaceInString(strTAB));           
        Console.WriteLine(RemoveWhiteSpaceInString(strTABandSpaces));  
    }                                                                  
      
    Output:  
      
    HasSpacesAfter    after                                                                                   
    HasTabsAfter            after            
    HasWhitespacesAfter               after  
    HasSpacesAfter after                     
    HasTabsAfter after                       
    HasWhitespacesAfter after                
      
      
    
    • Wayne
    0 comments No comments

  3. Najmul Islam Naeem 0 Reputation points
    2025-01-01T21:11:46.68+00:00

    s=" Bob Loves Alice "

    string[] allwords = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.