C # Remove string Spaces

Source: Internet
Author: User
(1) trim method

String TT = "AAA ";

Tt = TT. Trim () function for removing spaces at the beginning and end of a string

Tt = TT. trimend () Remove the trailing space of the string

Tt = TT. trimstart () Remove the first space of the string

(2) Remove spaces from characters using ASCII values

Since the ASCII value of space is 32, when removing all spaces in the string, you only need to cyclically access all characters in the string and determine whether their ASCII value is 32. Remove all spaces in the string.CodeAs follows:

Charenumerator cenumerator = textbox1.text. getenumerator ();

While (cenumerator. movenext ())

{

Byte [] array = new byte [1];

Array = system. Text. encoding. ASCII. getbytes (cenumerator. Current. tostring ());

Int asciicode = (short) (array [0]);

If (asciicode! = 32)

{

Textbox2.text + = cenumerator. Current. tostring ();

}

}

The three methods can only remove halfwidth spaces, but not fullwidth spaces.

(3) Replace Method

Use the replace method that comes with the string: Str. Replace ("", "") ----------- STR is the input or the string to be checked.

# Replace function. Note the following for its parameters:

If its parameter is an expression, the system first computes the expression for preprocessing and then performs the replacement operation.

For example, (getnamebyid is a function ):

String strsource = "this is an example ";

Strsource = strsource. Replace ("name", getnamebyid (1 ));

Obviously, strsource does not contain "name", so it will not be replaced. However, getnamebyid is called every time this line of code is replaced. If getnamebyid is more complex logic, or the replacement operation is in a loop, the system efficiency will be greatly affected.

Recommended:

If (strsource. indexof ("name")>-1)

{

Strsource = strsource. Replace ("name", getnamebyid (1 ));

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.