Remove spaces from a string

Source: Internet
Author: User

1) Trim method

String tt= "AAA";

Tt=tt. Trim () function to go to string end and end spaces

Tt=tt. TrimEnd () Remove string trailing spaces

Tt=tt. TrimStart () Remove string first space

(2) Remove whitespace from characters by ASCII code value

Because the ASCII value of the space is 32, when you remove all the spaces in the string, you simply iterate through all the characters in the string and determine if their ASCII value is 32. The key code to remove all the spaces in the string is as follows:

Charenumerator CEnumerator = textBox1.Text.GetEnumerator ();  while (Cenumerator.movenext ()) {bytenewbyte[1=  System.Text.Encoding.ASCII.GetBytes (CEnumerator.Current.ToString ()); int Asciicode = (short) (array[0]); if  +  + = CEnumerator.Current.ToString ();}}

(3) Replace method

Use the Replace method with the string's own: Str.replace ("", "")-------------str is the string to be entered or to be detected.

#的Replace函数, you need to be aware of its parameters:

If its argument is an expression, the system evaluates the expression before preprocessing, and then performs the substitution 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 no substitution is performed. However, every time this line of substitution code is executed, Getnamebyid will be called once.  If Getnamebyid is a more complex logic, or if the substitution operation is in a loop, it will greatly affect the efficiency of the system. Suggested changes to:if(Strsource.indexof ("name") >-1) {strsource=strsource.replace ("name", Getnamebyid (1)); }

Here are 3 ways to remove only half-width space, not to remove the full-width space.

Remove spaces from a string

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.