【问题标题】:How to count the number of spaces and characters in vb.net?如何计算vb.net中的空格和字符数?
【发布时间】:2014-08-30 10:47:43
【问题描述】:

我想计算文本框字段中输入的空格和字符的数量。 示例

 textbox1.text - " 1 2 3 4 5 6 7 a b c"

我要数空格数和字符数

那么结果一定是..

将空格作为整数,char 作为整数

空格 = 10 , 字符 = 10

【问题讨论】:

标签: vb.net


【解决方案1】:
 Dim spaceCount, lettercount As Integer
 spaceCount= 0
 lettercount = 0
 Dim s As String = " 1 2 3 4 5 6 7 a b c"
 For Each c As Char In s
    If c = " " Then
        spaceCount+= 1
    Else
        lettercount += 1
    End If
 Next
 MsgBox(charcount)
 MsgBox(lettercount)

For Each 将遍历string 中的每个字符,然后检查c 是否为空格。如果是空格则增加spaceCount 否则增加lettrtCount

【讨论】:

  • 您可能希望将If c = " " Then 更改为If c = " "c Then。我不确定它是否会在 Option Strict On 下编译。
【解决方案2】:

你可以按照你想要的方式做。

试试看

Dim count As Integer = 0
textbox1.text = " 1 2 3 4 5 6 7 a b c"
count = textbox1.text.Split(" ").Length -1

【讨论】:

    【解决方案3】:
    Dim longstring As String = "aab c d e" 
    Dim TotalLength As Integer = longstring.Length
    Dim TotalSpaces() As String = Split(longstring, " "
    Dim TotalChars As Integer = TotalLength - (TotalSpaces.Length - 1)
    

    【讨论】:

    • 描述一下你在这里做什么以及这将如何帮助解决问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 2012-05-13
    • 2015-08-13
    • 2013-07-22
    相关资源
    最近更新 更多