ZetCode

Visual Basic 字符串

最后修改于 2023 年 10 月 18 日

在本 Visual Basic 教程中,我们将学习字符串数据类型。

字符串是由 0 到 65535 之间的无符号 16 位代码点序列组成的。

第一个示例

字符串字面量是表示计算机程序文本中字符串值的表示法。在 Visual Basic 中,字符串字面量用双引号括起来。 Visual Basic 中的字符串是 Unicode 字符的序列。

Program.vb
Option Strict On

Module Example

    Sub Main()

        Dim str1 As String = "There are 10"
        Dim str2 As String = " apples"

        Console.WriteLine(str1 + str2)

        Console.WriteLine("The length of the first string is " +
             str1.Length.ToString() + " characters")

    End Sub

End Module

在前面的示例中,我们创建了两个字符串变量。然后我们把它们加起来,并计算第一个字符串的长度。

Dim str1 As String = "There are 10"

声明并初始化一个字符串变量。

Console.WriteLine(str1 + str2)

两个字符串被连接起来。我们使用 + 运算符将两个字符串相加。

Console.WriteLine("The length of the first string is " +
    str1.Length.ToString() + " characters")

使用 Length 属性来确定字符串的长度。

$ dotnet run
There are 10 apples
The length of the first string is 12 characters

使用引号

双引号用于在 Visual Basic 中创建字符串字面量。如果我们想显示引号,例如在直接引用中,该怎么办?要打印双引号,必须在其前面加上另一个双引号。

Program.vb
Option Strict On

Module Example

    Sub Main()

        Console.WriteLine("There are many stars.")
        Console.WriteLine("He said, ""Which one is your favourite?""")

    End Sub

End Module

当将双引号打印到控制台时,它们必须在其前面加上另一个双引号。

Console.WriteLine("He said, ""Which one is your favourite?""")

在这里,我们展示了如何将直接引用打印到控制台。如果我们不使用两个双引号,编译器就会被误导。它会看到两个连续的字符串。

$ dotnet run
There are many stars.
He said, "Which one is your favourite?"

多行字符串

可以在 Visual Basic 中创建一个多行字符串。

Program.vb
Option Strict On

Module Example

    Sub Main()

        Dim multiLine As String = "Not marble nor the gilded monuments
Of princes shall outlive this powerful rhyme,
But you shall shine more bright in these contents
Than unswept stone besmeared with sluttish time.
When wasteful war shall statues overturn,
And broils root out the work of masonry,
Nor Mars his sword nor war's quick fire shall burn
The living record of your memory.
'Gainst death and all-oblivious enmity
Shall you pace forth; your praise shall still find room
Even in the eyes of all posterity
That wear this world out to the ending doom.
So, till the Judgement that yourself arise,
You live in this, and dwell in lovers' eyes."

        Console.WriteLine(multiLine)

    End Sub

End Module

该示例创建了一个跨越多行的字符串。从 Visual Basic 14 开始,也可以使用单引号来创建多行字符串。

$ dotnet run 
Not marble nor the gilded monuments
Of princes shall outlive this powerful rhyme,
But you shall shine more bright in these contents
Than unswept stone besmeared with sluttish time.
...

比较字符串

字符串可以使用数值比较运算符和 Like 运算符进行比较。

Program.vb
Option Strict On

Module Example

    Sub Main()

        Console.WriteLine("12" = "12") 'Returns True
        Console.WriteLine("17" < "9") ' Returns True
        Console.WriteLine("aa" > "ab") ' Returns False

    End Sub

End Module

比较运算符在字符串上下文中工作方式不同。

Console.WriteLine("17" < "9") 'Returns True

值 17 不小于 9。但是当在两个字符串上应用 < 时,我们不比较数字。我们比较字符的排序顺序。1 在 9 之前,因此它具有“较低的位置”,比较返回 True。

Console.WriteLine("aa" > "ab") ' Returns False

如果前两个字符相等,则该操作将继续对后续字符进行。字符 a 在字符 b 之前,比较操作返回 False。

String.Compare 比较两个指定的字符串,并返回一个整数,该整数指示它们在排序顺序中的相对位置。如果返回的值小于零,则第一个字符串小于第二个字符串。如果返回零,则两个字符串相等。最后,如果返回的值大于零,则第一个字符串大于第二个字符串。

Program.vb
Option Strict On

Module Example

    Sub Main()

        Dim str1 As String = "Visual Basic"
        Dim str2 As String = "visual basic"

        Console.WriteLine(String.Compare(str1, str2, True))
        Console.WriteLine(String.Compare(str1, str2, False))

    End Sub

End Module

有一个可选的第三个 ignoreCase 参数,用于确定是否应该遵守大小写。

Console.WriteLine(String.Compare(str1, str2, True))

比较两个字符串并忽略大小写。此行将 0 打印到控制台。

Like 运算符可用于简单的正则表达式匹配。

Program.vb
Option Strict On

Module Example

    Dim words() As String = {"Seven", "even", "Maven", "Amen", "Leven"}

    Sub Main()

        For Each word As String In words
            If word Like "?*even" Then
                Console.WriteLine("{0} matches the pattern", word)
            Else
                Console.WriteLine("{0} does not match the pattern", word)
            End If
        Next

    End Sub

End Module

我们有一个单词数组。我们根据正则表达式模式测试这些单词。如果单词匹配或不匹配,我们将消息打印到控制台。

Dim words() As String = {"Seven", "even", "Maven", "Amen", "Leven"}

这是一个包含五个单词的数组。

For Each word As String In words
    ...
Next

我们使用 For Each 循环遍历数组。当前单词存储在单词变量中。

If word Like ".*even" Then
    Console.WriteLine("{0} matches the pattern", word)
Else
    Console.WriteLine("{0} does not match the pattern", word)
End If

“?*even”是一个简单的正则表达式模式。? 匹配任何单个字符,* 匹配零个或多个字符。我们打印一条消息来告知单词是否与模式匹配。

字符串函数

Visual Basic 具有有用的内置函数,可用于处理字符串。

Program.vb
Option Strict On

Module Example

    Sub Main()

        Dim str As String = "Visual Basic"

        Dim n As Integer = Len(str)
        Dim l As String = Left(str, 6)
        Dim r As String = Right(str, 5)
        Dim repl As String = Replace(str, "Basic", "form")

        Console.WriteLine("The string has {0} characters", n)
        Console.WriteLine("The Left function returns {0}", l)
        Console.WriteLine("The Right function returs {0}", r)
        Console.WriteLine("The Replace function returns {0}", repl)

    End Sub

End Module

我们在 Visual Basic 中介绍了四个字符串函数。

Dim n As Integer = Len(str)

Len 函数返回字符串中的字符数。

Dim l As String = Left(str, 6)

此对 Left 函数的调用返回字符串左侧的 6 个字符。在我们的例子中,“Visual”。

Dim r As String = Right(str, 5)

这里我们从右边获取 5 个字符。

Dim repl As String = Replace(str, "Basic", "form")

字符串在 Visual Basic 中是不可变的。当我们使用 Replace 函数时,我们返回一个新的修改后的字符串,其中第一个字符串被替换为第二个字符串。

$ dotnet run
The string has 12 characters
The Left function returns Visual
The Right function returs Basic
The Replace function returns Visual form

JoinSplit 函数是非常方便的函数。

Program.vb
Option Strict On

Imports System


Module Example

    Sub Main()

        Dim items() As String = {"C#", "Visual Basic", "Java", "Perl"}

        Dim langs As String = Join(items, ",")
        Console.WriteLine(langs)

        Dim ls() As String = Split(langs, ",")

        For Each lang As String In ls
            Console.WriteLine(lang)
        Next

    End Sub

End Module

在我们的程序中,我们使用这两个函数连接和分割字符串。

Dim langs As String = Join(items, ",")

数组中的所有单词都被连接起来。我们从它们构建一个字符串。每个两个单词之间都会有一个逗号字符。

Dim ls() As String = Split(langs, ",")

作为逆操作,我们拆分 langs 字符串。Split 函数返回一个单词数组,以字符分隔。在我们的例子中,它是一个逗号字符。

For Each lang As String In ls
    Console.WriteLine(lang)
Next

我们遍历数组并打印其元素。

$ dotnet run
C#,Visual Basic,Java,Perl
C#
Visual Basic
Java
Perl

字符串方法

除了字符串函数,还有几个字符串方法。其中一些方法提供相同的功能。正如我们已经提到的,字符串不是原始数据类型。它们是引用类型。它们是对象,这些对象具有可以完成一些工作的方法。

Program.vb
Option Strict On

Imports System


Module Example

    Sub Main()

        Dim str As String = "Determination"

        Console.WriteLine(str.Contains("e"))
        Console.WriteLine(str.IndexOf("e"))
        Console.WriteLine(str.LastIndexOf("i"))

        Console.WriteLine(str.ToUpper)
        Console.WriteLine(str.ToLower)

    End Sub

End Module

我们在上面的例子中介绍了五个字符串方法。

Console.WriteLine(str.Contains("e"))

如果字符串包含特定字符,则 Contains 方法返回 True。

Console.WriteLine(str.IndexOf("e"))

IndexOf 返回字符串中字母的第一个索引。

Console.WriteLine(str.LastIndexOf("i"))

LastIndexOf 方法返回字符串中字母的最后一个索引。

Console.WriteLine(str.ToUpper)
Console.WriteLine(str.ToLower)

字符串的字母使用 ToUpper 方法转换为大写,使用 ToLower 方法转换为小写。

$ dotnet run
True
1
10
DETERMINATION
determination

复制 vs 克隆

Copy 方法使用与指定字符串相同的值创建一个新的字符串实例。Clone 方法返回对正在克隆的字符串的引用。它不是堆上字符串的独立副本;它是对同一字符串的另一个引用。

Program.vb
Option Strict On

Module Example

    Sub Main()

        Dim str As String = "Visual Basic"

        Dim cloned As String = CType(str.Clone(), String)
        Dim copied As String = String.Copy(str)

        Console.WriteLine(str = cloned) ' Prints True
        Console.WriteLine(str = copied) ' Prints True

        Console.WriteLine(str Is cloned) ' Prints True
        Console.WriteLine(str Is copied) ' Prints False


    End Sub

End Module

我们的示例演示了这两种方法之间的区别。

Dim cloned As String = CType(str.Clone(), String)
Dim copied As String = String.Copy(str)

字符串值被克隆并复制。

Console.WriteLine(str = cloned) ' Prints True
Console.WriteLine(str = copied) ' Prints True

所有三个字符串的内容都是相同的。

Console.WriteLine(str Is cloned) ' Prints True
Console.WriteLine(str Is copied) ' Prints False

Is 运算符比较两个引用对象。因此,将复制的字符串与原始字符串进行比较会返回 False。因为它们是两个不同的对象。

格式化字符串

在下一个示例中,我们格式化字符串。.NET Framework 具有一个称为复合格式化的功能。它受 FormatWriteLine 方法的支持。一种方法将对象列表和复合格式字符串作为输入。格式字符串由固定字符串加上一些格式项组成。这些格式项是索引占位符,它们对应于列表中的对象。

格式项具有以下语法

{index[,length][:formatString]}

索引组件是必需的。它是一个从 0 开始的数字,引用对象列表中的一个项目。多个项目可以引用对象列表中的同一元素。如果格式项未引用对象,则忽略该对象。如果我们引用对象列表的范围之外,则会引发运行时异常。

长度组件是可选的。它是一个参数的字符串表示形式中的最小字符数。如果为正数,则参数右对齐;如果为负数,则参数左对齐。如果指定了它,则必须用冒号分隔索引和长度。

formatString 是可选的。它是一个以特定方式格式化值的字符串。它可用于格式化日期、时间和数字或枚举。

在这里,我们展示了如何使用格式项的长度组件。我们将三列数字打印到终端。左对齐、居中对齐和右对齐。

Program.vb
Option Strict On

Imports System


Module Example

    Dim oranges As Byte = 2
    Dim apples As Byte = 4
    Dim bananas As Byte = 3

    Sub Main()

        Dim str1 As String = "There are {0} oranges, {1} apples and " +
            "{2} bananas"

        Dim str2 As String = "There are {1} oranges, {2} bananas and " +
            "{0} apples"

        Console.WriteLine(str1, oranges, apples, bananas)
        Console.WriteLine(str2, apples, oranges, bananas)

    End Sub

End Module

我们将一条简单的消息打印到控制台。 我们仅使用格式项的 index 组件。

Dim str1 As String = "There are {0} oranges, {1} apples and " +
    "{2} bananas"

{0}{1}{2} 是格式项。我们指定索引组件。其他组件是可选的。

Console.WriteLine(str1, oranges, apples, bananas)

现在我们一起构成复合格式化。我们有字符串和对象列表(橙子、苹果、香蕉)。{0} 格式项引用橙子。WriteLine 方法将 {0} 格式项替换为橙子变量的内容。

Dim str2 As String = "There are {1} oranges, {2} bananas and " +
    "{0} apples"

格式项引用对象的顺序不是重要的。

$ dotnet run
There are 2 oranges, 4 apples and 3 bananas
There are 2 oranges, 3 bananas and 4 apples
Program.vb
Option Strict On

Module Example

    Sub Main()

        Console.WriteLine("{0}  {1, 12}", "Decimal", "Hexadecimal")

        Console.WriteLine("{0:D}  {1,8:X}", 502, 546)
        Console.WriteLine("{0:D}  {1,8:X}", 345, 765)
        Console.WriteLine("{0:D}  {1,8:X}", 320, 654)
        Console.WriteLine("{0:D}  {1,8:X}", 120, 834)
        Console.WriteLine("{0:D}  {1,8:X}", 620, 454)

    End Sub

End Module

我们以十进制和十六进制格式打印数字。 我们还使用 length 组件对齐数字。

Console.WriteLine("{0:D}  {1,8:X}", 502, 546)

{0:D} 格式项指定将从提供的对象列表中获取第一个项目,并以十进制格式进行格式化。{1,8:X} 格式项获取第二个项目。将其格式化为十六进制格式 (:X)。并且字符串长度将为 8 个字符 ,8。由于数字只有三个字符,因此它右对齐并用空字符串填充。

$ dotnet run
Decimal   Hexadecimal
502       222
345       2FD
320       28E
120       342
620       1C6

最后两个示例格式化数值和日期数据。

Program.vb
Option Strict On

Module Example

    Sub Main()

        Console.WriteLine(String.Format("Number: {0:N}", 126))
        Console.WriteLine(String.Format("Scientific: {0:E}", 126))
        Console.WriteLine(String.Format("Currency: {0:C}", 126))
        Console.WriteLine(String.Format("Percent: {0:P}", 126))
        Console.WriteLine(String.Format("Hexadecimal: {0:X}", 126))

    End Sub

End Module

该示例演示了数字的标准格式说明符。数字 126 以五种不同的格式打印;普通、科学、货币、百分比和十六进制。

$ dotnet run
Number: 126.000
Scientific: 1.260000E+002
Currency: $126.00
Percent: 12,600.000%
Hexadecimal: 7E

最后,我们格式化日期和时间数据。

Program.vb
Option Strict On

Module Example

    Sub Main()

        Dim today As DateTime = DateTime.Now()

        Console.WriteLine(String.Format("Short date: {0:d}", today))
        Console.WriteLine(String.Format("Login date: {0:D}", today))
        Console.WriteLine(String.Format("Short time: {0:t}", today))
        Console.WriteLine(String.Format("Long time: {0:T}", today))
        Console.WriteLine(String.Format("Month: {0:M}", today))
        Console.WriteLine(String.Format("Year: {0:Y}", today))

    End Sub

End Module

前面的示例演示了日期的标准格式说明符。

$ dotnet run
Short date: 9/3/2022
Login date: Saturday, September 3, 2022
Short time: 12:05 PM
Long time: 12:05:02 PM
Month: September 3
Year: September 2022

本 Visual Basic 教程涵盖了字符串。