Use the Split and Replace functions in VB. NET to calculate the number of words

Source: Internet
Author: User

The Split function allows you to separate long strings into separate words. However, if there is more than one space between words, Split returns an error. To prevent this, you can use the Replace function to Replace multiple spaces before using Split. List A provides an example.

List

Private Sub CountWords () Dim strText As String = "It's a wonderful world" Dim iCount As IntegerDo While (strText. indexOf (Space (2)> = 0) strText = strText. replace (Space (2), Space (1) LoopiCount = Split (strText, Space (1 )). lengthMsgBox (iCount. toString () End Sub

In this example, I created the strText string and set it to a long string with multiple characters. Then, I use the Replace function to Replace multiple spaces with one. This is done to prepare the string strText so that you can use the Split function and provide the correct results.

Then, I input strText into the Split function and get the number of words included in the string strText. Note: If you skip or annotate the loop to Remove extra spaces, the result is 7 words. The result is correct after all the unnecessary spaces are removed.

Private Sub CountWords () Dim strText As String = "It's a wonderful world" Dim iCount As IntegerDo While (strText. indexOf (Space (2)> = 0) strText = strText. replace (Space (2), Space (1) LoopiCount = Split (strText, Space (1 )). length MsgBox (iCount. toString () End Sub

 

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.