none
Trimming Strings

    คำถาม

  • 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.



    • แก้ไขโดย Nevin Janzen 7 มีนาคม 2555 3:52
    7 มีนาคม 2555 3:18

คำตอบ

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

    • ทำเครื่องหมายเป็นคำตอบโดย Nevin Janzen 13 มีนาคม 2555 22:13
    7 มีนาคม 2555 3:50
  • 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!

    • ทำเครื่องหมายเป็นคำตอบโดย Nevin Janzen 13 มีนาคม 2555 22:12
    7 มีนาคม 2555 5:03
  • 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)



    • แก้ไขโดย Jean Paul V.A 7 มีนาคม 2555 5:15
    • ทำเครื่องหมายเป็นคำตอบโดย Nevin Janzen 13 มีนาคม 2555 22:12
    7 มีนาคม 2555 5:14
  • 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"

    • ทำเครื่องหมายเป็นคำตอบโดย Nevin Janzen 13 มีนาคม 2555 22:06
    7 มีนาคม 2555 5:41
  • 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".

    • ทำเครื่องหมายเป็นคำตอบโดย Nevin Janzen 13 มีนาคม 2555 22:06
    7 มีนาคม 2555 10:49
  • 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".


    • แก้ไขโดย orichisonic 8 มีนาคม 2555 7:23
    • ทำเครื่องหมายเป็นคำตอบโดย Nevin Janzen 13 มีนาคม 2555 22:04
    8 มีนาคม 2555 7:22
  • 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.



    • แก้ไขโดย Nevin Janzen 7 มีนาคม 2555 4:01
    • ทำเครื่องหมายเป็นคำตอบโดย Nevin Janzen 13 มีนาคม 2555 22:13
    7 มีนาคม 2555 3:58

ตอบทั้งหมด

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

    • ทำเครื่องหมายเป็นคำตอบโดย Nevin Janzen 13 มีนาคม 2555 22:13
    7 มีนาคม 2555 3:50
  • 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.



    • แก้ไขโดย Nevin Janzen 7 มีนาคม 2555 4:01
    • ทำเครื่องหมายเป็นคำตอบโดย Nevin Janzen 13 มีนาคม 2555 22:13
    7 มีนาคม 2555 3:58
  • 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.


    • แก้ไขโดย Nevin Janzen 7 มีนาคม 2555 4:25
    7 มีนาคม 2555 4:11
  • REGEX will do it too.

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


    JP Cowboy Coders Unite!

    7 มีนาคม 2555 4:27
  • 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.


    • แก้ไขโดย Nevin Janzen 7 มีนาคม 2555 4:45
    7 มีนาคม 2555 4:40
  • 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!

    • ทำเครื่องหมายเป็นคำตอบโดย Nevin Janzen 13 มีนาคม 2555 22:12
    7 มีนาคม 2555 5:03
  • 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)



    • แก้ไขโดย Jean Paul V.A 7 มีนาคม 2555 5:15
    • ทำเครื่องหมายเป็นคำตอบโดย Nevin Janzen 13 มีนาคม 2555 22:12
    7 มีนาคม 2555 5:14
  • 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"

    • ทำเครื่องหมายเป็นคำตอบโดย Nevin Janzen 13 มีนาคม 2555 22:06
    7 มีนาคม 2555 5:41
  • 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".

    • ทำเครื่องหมายเป็นคำตอบโดย Nevin Janzen 13 มีนาคม 2555 22:06
    7 มีนาคม 2555 10:49
  • Using a regular expression to remove leading and trailing blanks:
    static string TrimWhitespace(string theString)
    {
        return Regex.Replace(theString, @"^\s*(.*?)\s*$", @"$1", RegexOptions.Singleline);
    }

    7 มีนาคม 2555 13:13
  • 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".


    • แก้ไขโดย orichisonic 8 มีนาคม 2555 7:23
    • ทำเครื่องหมายเป็นคำตอบโดย Nevin Janzen 13 มีนาคม 2555 22:04
    8 มีนาคม 2555 7:22
  • 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.

    13 มีนาคม 2555 22:04