none
Trimming Strings

    Question

  • Hi, I have this code:

    static string TrimWhitespace(string theString)
    {
        string result = "";
        //remove whitespace chars from string...
        return result;
    }

    I want to trim the whitespace off both ends of the string. How I can do this without using the System.String.Trim method?

    Thanks!!

    P.S.  For those who do not know, whitespace characters include spaces (' '), newlines ('\n'), carriage returns ('\r'), tabs ('\t'), vetical tabs ('\v'), and form feeds ('\f'). Please let me know if I am missing any.


    Nevin Janzen (Visit my Website)
    If this post answers your question, please click Propose As Answer. If this post is helpful, please click Vote As Helpful.



    Wednesday, March 07, 2012 3:18 AM

Answers

  • var value = "with whitespace";
    var chars = from c in value where c != ' ' select c;
    var newValue = new string(chars.ToArray());
    // value is "withwhitespace";

    • Marked as answer by Nevin Janzen Tuesday, March 13, 2012 10:13 PM
    Wednesday, March 07, 2012 3:50 AM
  • Woops try this:

    //Namespace Reference
    using System.Text.RegularExpressions;
    
    /// <summary>
    /// Method for removing trailing and leadingt whitespace from a string
    /// </summary>
    /// <param name="str">The string to trim</param>
    /// <returns></returns>
    public string TrimString(string str)
    {
        try
        {
            string pattern = @"^[ \t]+|[ \t]+$";
            Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);
            str = reg.Replace(str, "");
            return str;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }


    JP Cowboy Coders Unite!

    • Marked as answer by Nevin Janzen Tuesday, March 13, 2012 10:12 PM
    Wednesday, March 07, 2012 5:03 AM
  • There is an overloaded method for Trim() which allows us to specify the characters to be trimmed as params

    Eg:

    var s = " abc\nte s t    ".Trim(' ');
    This makes sure only the leading and trailing characters are trimmed.


    Resolving n Evolving in C# (http://jeanpaulva.com)



    • Edited by Jean Paul V.A Wednesday, March 07, 2012 5:15 AM
    • Marked as answer by Nevin Janzen Tuesday, March 13, 2012 10:12 PM
    Wednesday, March 07, 2012 5:14 AM
  • Hi ..

     TrimEnd and TrimStart is used to remove the empty space for  whitespace off both ends of the string.

     static string TrimWhitespace(string theString)
            {
                theString = " Welcoem you to\n MSDN Forum ";
                theString = theString.TrimEnd();
                theString = theString.TrimStart();
                MessageBox.Show(theString, "");
                return theString;
            }

    If you dont want to use TrimStart and TrimEnd use the below code and it works well for me.

     private void Form1_Load(object sender, EventArgs e)
            {
                String s = " Welcoem you \n to MSDN Forum ";
                String[] SubString = s.Split(new char[] { ' ' });
                String Result = "";
                int EndPos = 0;
                int StartPos = 0;
                for (int i = 0; i <= SubString.Length -1 ; i++)
                {
                    if (String.IsNullOrEmpty(SubString[i]))
                    {}
                    else
                    {
                        StartPos = i;
                        break;
                    }
                }
                for (int j = SubString.Length - 1; j >= 0; j--)
                {
                    if ( String.IsNullOrEmpty(SubString[j]))
                    {}
                    else
                    { EndPos = j;
                    break;
                    }
                }
                for (int k= StartPos; k <= EndPos; k++)
                {
                    Result = Result + " " + SubString[k];
                }
                MessageBox.Show(Result, "");
              
            }


    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful"

    • Marked as answer by Nevin Janzen Tuesday, March 13, 2012 10:06 PM
    Wednesday, March 07, 2012 5:41 AM
  • Hi, 

    Trim provides the functionality you asked for right ? if this is not sufficient you have to find index of first non empty char and last non empty char indexes and substring

    pseudo code can be like,

     public static int LastNonWhiteSpaceCharIndexArray(this char[] charArray)
            {
                return charArray.Length - (charArray.Reverse().ToArray().FirstNonWhiteSpaceCharIndexArray() + 1);
            }
            public static int FirstNonWhiteSpaceCharIndexArray(this char[] charArray)
            {
                for (int i = 0; i < charArray.Length; i++)
                    if (!char.IsWhiteSpace(charArray[i]))
                        return i;
                return 0;
            }

    Hope this helps you...


    If this post answers your question, please click "Mark As Answer". If this post is helpful please click "Mark as Helpful".

    • Marked as answer by Nevin Janzen Tuesday, March 13, 2012 10:06 PM
    Wednesday, March 07, 2012 10:49 AM
  • Hi Nevin Janzen,

      I have used the Regular Expression tool named "The Regulator" testing the above regular expression, it seems that @Louis.fr's reply is completely suitable for your requirement. Furthermore, Regex.Replace override function uses the following format:

      http://msdn.microsoft.com/en-us/library/ms149475.aspx 

      Besides that, I notice you have unproposed this reply as an answer.Please feel free to let me know what your suggestion is. We are happy to follow your directions to continue discussions.

      Sincerely,

      Jason Wang


    orichisonic http://blog.csdn.net/orichisonic If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".


    • Edited by orichisonic Thursday, March 08, 2012 7:23 AM
    • Marked as answer by Nevin Janzen Tuesday, March 13, 2012 10:04 PM
    Thursday, March 08, 2012 7:22 AM
  • How would I make this work for all the whitespace characters? How about the following (I just did the '\n' character and excluded the rest except for ' '):

    var value = "Whitespace: \n";
    var chars = from c in value where (c != ' ' && c != '\n') select c;
    var newValue = new string(chars.ToArray());
    // value is "Whitespace:"


    Nevin Janzen (Visit my Website)
    If this post answers your question, please click Propose As Answer. If this post is helpful, please click Vote As Helpful.



    • Edited by Nevin Janzen Wednesday, March 07, 2012 4:01 AM
    • Marked as answer by Nevin Janzen Tuesday, March 13, 2012 10:13 PM
    Wednesday, March 07, 2012 3:58 AM

All replies

  • var value = "with whitespace";
    var chars = from c in value where c != ' ' select c;
    var newValue = new string(chars.ToArray());
    // value is "withwhitespace";

    • Marked as answer by Nevin Janzen Tuesday, March 13, 2012 10:13 PM
    Wednesday, March 07, 2012 3:50 AM
  • How would I make this work for all the whitespace characters? How about the following (I just did the '\n' character and excluded the rest except for ' '):

    var value = "Whitespace: \n";
    var chars = from c in value where (c != ' ' && c != '\n') select c;
    var newValue = new string(chars.ToArray());
    // value is "Whitespace:"


    Nevin Janzen (Visit my Website)
    If this post answers your question, please click Propose As Answer. If this post is helpful, please click Vote As Helpful.



    • Edited by Nevin Janzen Wednesday, March 07, 2012 4:01 AM
    • Marked as answer by Nevin Janzen Tuesday, March 13, 2012 10:13 PM
    Wednesday, March 07, 2012 3:58 AM
  • Is the above correct??


    Nevin Janzen (Visit my Website)
    If this post answers your question, please click Propose As Answer. If this post is helpful, please click Vote As Helpful.


    Wednesday, March 07, 2012 4:11 AM
  • REGEX will do it too.

     string NewTrimmedString = Regex.Replace(value, @"\s+", " ");
     


    JP Cowboy Coders Unite!

    Wednesday, March 07, 2012 4:27 AM
  • Yes, but I want it to only trim the leading and trailing whitespace. Is that what your regular expression does?


    Nevin Janzen (Visit my Website)
    If this post answers your question, please click Propose As Answer. If this post is helpful, please click Vote As Helpful.


    Wednesday, March 07, 2012 4:40 AM
  • Woops try this:

    //Namespace Reference
    using System.Text.RegularExpressions;
    
    /// <summary>
    /// Method for removing trailing and leadingt whitespace from a string
    /// </summary>
    /// <param name="str">The string to trim</param>
    /// <returns></returns>
    public string TrimString(string str)
    {
        try
        {
            string pattern = @"^[ \t]+|[ \t]+$";
            Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);
            str = reg.Replace(str, "");
            return str;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }


    JP Cowboy Coders Unite!

    • Marked as answer by Nevin Janzen Tuesday, March 13, 2012 10:12 PM
    Wednesday, March 07, 2012 5:03 AM
  • There is an overloaded method for Trim() which allows us to specify the characters to be trimmed as params

    Eg:

    var s = " abc\nte s t    ".Trim(' ');
    This makes sure only the leading and trailing characters are trimmed.


    Resolving n Evolving in C# (http://jeanpaulva.com)



    • Edited by Jean Paul V.A Wednesday, March 07, 2012 5:15 AM
    • Marked as answer by Nevin Janzen Tuesday, March 13, 2012 10:12 PM
    Wednesday, March 07, 2012 5:14 AM
  • Hi ..

     TrimEnd and TrimStart is used to remove the empty space for  whitespace off both ends of the string.

     static string TrimWhitespace(string theString)
            {
                theString = " Welcoem you to\n MSDN Forum ";
                theString = theString.TrimEnd();
                theString = theString.TrimStart();
                MessageBox.Show(theString, "");
                return theString;
            }

    If you dont want to use TrimStart and TrimEnd use the below code and it works well for me.

     private void Form1_Load(object sender, EventArgs e)
            {
                String s = " Welcoem you \n to MSDN Forum ";
                String[] SubString = s.Split(new char[] { ' ' });
                String Result = "";
                int EndPos = 0;
                int StartPos = 0;
                for (int i = 0; i <= SubString.Length -1 ; i++)
                {
                    if (String.IsNullOrEmpty(SubString[i]))
                    {}
                    else
                    {
                        StartPos = i;
                        break;
                    }
                }
                for (int j = SubString.Length - 1; j >= 0; j--)
                {
                    if ( String.IsNullOrEmpty(SubString[j]))
                    {}
                    else
                    { EndPos = j;
                    break;
                    }
                }
                for (int k= StartPos; k <= EndPos; k++)
                {
                    Result = Result + " " + SubString[k];
                }
                MessageBox.Show(Result, "");
              
            }


    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful"

    • Marked as answer by Nevin Janzen Tuesday, March 13, 2012 10:06 PM
    Wednesday, March 07, 2012 5:41 AM
  • Hi, 

    Trim provides the functionality you asked for right ? if this is not sufficient you have to find index of first non empty char and last non empty char indexes and substring

    pseudo code can be like,

     public static int LastNonWhiteSpaceCharIndexArray(this char[] charArray)
            {
                return charArray.Length - (charArray.Reverse().ToArray().FirstNonWhiteSpaceCharIndexArray() + 1);
            }
            public static int FirstNonWhiteSpaceCharIndexArray(this char[] charArray)
            {
                for (int i = 0; i < charArray.Length; i++)
                    if (!char.IsWhiteSpace(charArray[i]))
                        return i;
                return 0;
            }

    Hope this helps you...


    If this post answers your question, please click "Mark As Answer". If this post is helpful please click "Mark as Helpful".

    • Marked as answer by Nevin Janzen Tuesday, March 13, 2012 10:06 PM
    Wednesday, March 07, 2012 10:49 AM
  • Using a regular expression to remove leading and trailing blanks:
    static string TrimWhitespace(string theString)
    {
        return Regex.Replace(theString, @"^\s*(.*?)\s*$", @"$1", RegexOptions.Singleline);
    }

    Wednesday, March 07, 2012 1:13 PM
  • Hi Nevin Janzen,

      I have used the Regular Expression tool named "The Regulator" testing the above regular expression, it seems that @Louis.fr's reply is completely suitable for your requirement. Furthermore, Regex.Replace override function uses the following format:

      http://msdn.microsoft.com/en-us/library/ms149475.aspx 

      Besides that, I notice you have unproposed this reply as an answer.Please feel free to let me know what your suggestion is. We are happy to follow your directions to continue discussions.

      Sincerely,

      Jason Wang


    orichisonic http://blog.csdn.net/orichisonic If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".


    • Edited by orichisonic Thursday, March 08, 2012 7:23 AM
    • Marked as answer by Nevin Janzen Tuesday, March 13, 2012 10:04 PM
    Thursday, March 08, 2012 7:22 AM
  • Thank you all for your suggestions, code samples, and time. I greatly appreciate it and I am very grateful for all the contributions. Up-votes for all of you!!

    Great job and thanks again!


    Nevin Janzen (Visit my Website)
    If this post answers your question, please click Propose As Answer. If this post is helpful, please click Vote As Helpful.

    Tuesday, March 13, 2012 10:04 PM