🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Visual Basic 中的字符串 > 原文: [https://zetcode.com/lang/visualbasic/strings/](https://zetcode.com/lang/visualbasic/strings/) 在 Visual Basic 教程的这一部分中,我们将更详细地处理字符串数据。 字符串是计算机语言中最重要的数据类型。 这就是为什么我们将一整章专门讨论在 Visual Basic 中使用字符串的原因。 ## 第一个例子 字符串字面值是表示计算机程序文本内的字符串值的符号。 在 Visual Basic 中,字符串字面值用双引号引起来。 Visual Basic 中的字符串是 Unicode 字符序列。 ```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 ``` 在前面的示例中,我们创建了两个字符串变量。 然后我们将它们相加并计算第一个字符串的长度。 ```vb Dim str1 As String = "There are 10" ``` 声明并初始化一个字符串变量。 ```vb Console.WriteLine(str1 + str2) ``` 两个字符串连接在一起。 我们使用`+`运算符添加两个字符串。 ```vb Console.WriteLine("The length of the first string is " _ + str1.Length.ToString() + " characters") ``` `Length`属性用于确定字符串的长度。 ```vb $ ./basics.exe There are 10 apples The length of the first string is 12 characters ``` 运行示例可得出此结果。 ## 使用引号 双引号用于在 Visual Basic 中创建字符串字面值。 如果我们想显示报价,例如直接讲话怎么办? 要打印双引号,必须在其前面加上另一个双引号。 ```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 ``` 在控制台上打印双引号时,必须在其前面加上另一个双引号。 ```vb Console.WriteLine("He said, ""Which one is your favourite?""") ``` 在这里,我们展示了如何将直接语音打印到控制台。 如果我们不使用两个双引号,则会误导编译器。 它会看到两个连续的字符串。 ```vb $ ./quotes.exe There are many stars. He said, "Which one is your favourite?" ``` 输出。 ## 多行字符串 可以在 Visual Basic 中创建多行字符串。 ```vb Option Strict On Module Example Sub Main() Dim multiString As String = "I cheated myself" + vbNewLine + _ "like I knew I would" + vbNewLine + _ "I told ya, I was trouble" + vbNewLine + _ "you know that I'm no good" Console.WriteLine(multiString) End Sub End Module ``` 该示例创建一个跨越多行的字符串。 我们使用换行符,加号和`vbNewLine`显示常量。 ```vb $ ./multiline.exe I cheated myself like I knew I would I told ya, I was trouble you know that I'm no good ``` 此文本以四行显示。 所有文本都分配给一个字符串变量。 ## 比较字符串 ```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 ``` 比较运算符在字符串上下文中的工作方式不同。 ```vb Console.WriteLine("17" < "9") 'Returns True ``` 值 17 不小于 9。但是在两个字符串上应用`<`时,我们不比较数字。 我们比较字符的排序顺序。 1 在 9 之前,因此具有“较低位置”,并且比较返回`True`。 ```vb Console.WriteLine("aa" > "ab") ' Returns False ``` 如果前两个字符相等,则继续对后两个字符进行操作。 a 字符位于 b 之前,并且比较操作返回`False`。 有`String.Compare()`方法,该方法比较两个指定的字符串并返回一个整数,该整数指示它们在排序顺序中的相对位置。 如果返回的值小于零,则第一个字符串小于第二个字符串。 如果返回零,则两个字符串相等。 最后,如果返回的值大于零,则第一个字符串大于第二个字符串。 ```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`参数确定是否应履行该案件。 ```vb Console.WriteLine(String.Compare(str1, str2, True)) ``` 比较两个字符串并忽略大小写。 此行将 0 打印到控制台。 有一个`Like`运算符,可用于简单的正则表达式匹配。 ```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 ``` 我们有很多单词。 我们将针对正则表达式模式测试这些单词。 如果单词匹配或不匹配,我们将向控制台打印一条消息。 ```vb Dim words() As String = {"Seven", "even", "Maven", "Amen", "Leven"} ``` 这是五个单词的数组。 ```vb For Each word As String In words ... Next ``` 我们使用`For Each`循环遍历数组。 当前单词存储在单词变量中。 ```vb 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 具有有用的内置函数,可用于处理字符串。 ```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 中引入了四个字符串函数。 ```vb Dim n As Integer = Len(str) ``` `Len()`函数返回字符串中的字符数。 ```vb Dim l As String = Left(str, 6) ``` 此`Left()`函数的调用从字符串的左侧返回 6 个字符。 在我们的例子中,`Visual`。 ```vb Dim r As String = Right(str, 5) ``` 在这里,我们从右边得到 5 个字符。 ```vb Dim repl As String = Replace(str, "Basic", "form") ``` 字符串在 Visual Basic 中是不可变的。 当我们使用`Replace()`函数时,我们返回一个新的修改后的字符串,其中第一个字符串替换为第二个字符串。 ```vb $ ./strfunc.exe The string has 12 characters The Left function returns Visual The Right function returs Basic The Replace function returns Visual form ``` 运行该示例将得出前面的结果。 `Join()`和`Split()`函数非常方便。 ```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 ``` 在我们的程序中,我们将使用这两个函数来连接和分割字符串。 ```vb Dim langs As String = Join(items, ",") ``` 数组中的所有单词都被加入。 我们从中构建一个字符串。 每两个字之间会有一个逗号。 ```vb Dim ls() As String = Split(langs, ",") ``` 作为反向操作,我们分割了`langs`字符串。 `Split()`函数返回一个由字符分隔的单词数组。 在我们的情况下,它是一个逗号字符。 ```vb For Each lang As String In ls Console.WriteLine(lang) Next ``` 我们遍历数组并打印其元素。 ```vb $ ./joinsplit.exe C#,Visual Basic,Java,Perl C# Visual Basic Java Perl ``` 示例的输出。 ## 字符串方法 除了字符串函数,还有几种字符串方法。 其中一些提供相同的功能。 正如我们已经提到的,字符串不是原始数据类型。 它们是引用类型。 它们是对象,这些对象具有可以完成某些工作的方法。 ```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 ``` 在上面的示例中,我们介绍了五个字符串方法。 ```vb Console.WriteLine(str.Contains("e")) ``` 如果字符串包含特定字符,则`Contains()`方法返回`True`。 ```vb Console.WriteLine(str.IndexOf("e")) ``` `IndexOf`返回字符串中字母的第一个索引。 ```vb Console.WriteLine(str.LastIndexOf("i")) ``` `LastIndexOf()`方法返回字符串中字母的最后一个索引。 ```vb Console.WriteLine(str.ToUpper) Console.WriteLine(str.ToLower) ``` 字符串的字母通过`ToUpper`方法转换为大写,并通过`ToLower`方法转换为小写。 ```vb $ ./strmethods.exe True 1 10 DETERMINATION determination ``` 运行程序。 ## 复制与克隆 我们将描述两种方法之间的区别。 复制并克隆。 `Copy()`方法创建一个新的`String`实例,该实例的值与指定的`String`相同。 `Clone()`方法返回对正在克隆的字符串的引用。 它不是堆上字符串的独立副本。 它是同一字符串上的另一个引用。 ```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 ``` 我们的示例演示了两种方法之间的区别。 ```vb Dim cloned As String = CType(str.Clone(), String) Dim copied As String = String.Copy(str) ``` 字符串值被克隆并复制。 ```vb Console.WriteLine(str = cloned) ' Prints True Console.WriteLine(str = copied) ' Prints True ``` 所有三个字符串的内容都是相同的。 ```vb Console.WriteLine(str Is cloned) ' Prints True Console.WriteLine(str Is copied) ' Prints False ``` `Is`运算符比较两个引用对象。 因此,将复制的字符串与原始字符串进行比较将返回`False`。 因为它们是两个不同的对象。 ## 格式化字符串 在下面的示例中,我们将格式化字符串。 .NET Framework 具有称为复合格式的功能。 `Format()`和`WriteLine()`方法支持它。 方法采用对象列表和复合格式字符串作为输入。 格式字符串由固定字符串加上一些格式项组成。 这些格式项是与列表中的对象相对应的索引占位符。 格式项具有以下语法: ```vb {index[,length][:formatString]} ``` 索引组件是必需的。 它是一个从 0 开始的数字,表示对象列表中的一项。 多个项目可以引用对象列表的同一元素。 如果格式项未引用该对象,则将其忽略。 如果我们在对象列表的范围之外引用,则会抛出运行时异常。 长度部分是可选的。 它是参数的字符串表示形式中的最小字符数。 如果为正,则该参数为右对齐;否则为 0。 如果为负,则为左对齐。 如果指定,则必须用冒号分隔索引和长度。 `formatString`是可选的。 它是一个格式化值的字符串,是一种特定的方式。 它可以用来格式化日期,时间,数字或枚举。 在这里,我们展示了如何使用格式项的长度分量。 我们将三列数字打印到终端。 左,中和右对齐。 ```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 ``` 我们向控制台打印一条简单的消息。 我们仅使用格式项的索引部分。 ```vb Dim str1 As String = "There are {0} oranges, {1} apples and " + _ "{2} bananas" ``` {0},{1}和{2}是格式项。 我们指定索引组件。 其他组件是可选的。 ```vb Console.WriteLine(str1, oranges, apples, bananas) ``` 现在,我们将复合格式放在一起。 我们有字符串和对象列表(橙色,苹果,香蕉)。 `{0}`格式项目是指橙色。 `WriteLine()`方法将`{0}`格式项替换为`oranges`变量的内容。 ```vb Dim str2 As String = "There are {1} oranges, {2} bananas and " + _ "{0} apples" ``` 引用对象的格式项的顺序很重要。 ```vb $ ./format1.exe There are 2 oranges, 4 apples and 3 bananas There are 2 oranges, 3 bananas and 4 apples ``` ```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 ``` 我们以十进制和十六进制格式打印数字。 我们还使用长度分量对齐数字。 ```vb Console.WriteLine("{0:D} {1,8:X}", _ 502, 546) ``` `{0:D}`格式项指定,将采用提供的对象列表中的第一项并将其格式化为十进制格式。 `{1,8:X}`格式项目取第二项。 将其格式化为十六进制格式`(:X)`。 字符串长度为 8 个字符`,8`。 因为数字只有三个字符,所以它会右对齐并用空字符串填充。 ```vb $ ./format2.exe Decimal Hexadecimal 502 222 345 2FD 320 28E 120 342 620 1C6 ``` 运行示例。 最后两个示例将格式化数字和日期数据。 ```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 以五种不同的格式打印。 正常,科学,货币,百分比和十六进制。 ```vb $ ./format3.exe Number: 126.00 Scientific: 1.260000E+002 Currency: $126.00 Percent: 12,600.00 % Hexadecimal: 7E ``` 输出。 最后,我们将格式化日期和时间数据。 ```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 ``` 前面的示例演示了日期的标准格式说明符。 ```vb $ ./format4.exe Short date: 8/18/2010 Login date: Wednesday, August 18, 2010 Short time: 11:29 PM Long time: 11:29:40 PM Month: August 18 Year: August, 2010 ``` Output. Visual Basic 教程的这一部分介绍了字符串。