Vb.net 将第一个单词小写
有人知道如何将文本框中每行的第一个单词小写吗 不是第一个字母,而是第一个单词 我试过这样做,但不起作用:Vb.net 将第一个单词小写,vb.net,word,lowercase,Vb.net,Word,Lowercase,有人知道如何将文本框中每行的第一个单词小写吗 不是第一个字母,而是第一个单词 我试过这样做,但不起作用: For Each iz As String In txtCode.Text.Substring(0, txtCode.Text.IndexOf(" ")) iz = LCase(iz) Next 代码的问题是,您只对整个文本框文本中第一个单词的每个字符运行循环 此代码在每行上循环,并取第一个单词: For Each line As String In txtCode.Text.S
For Each iz As String In txtCode.Text.Substring(0, txtCode.Text.IndexOf(" "))
iz = LCase(iz)
Next
代码的问题是,您只对整个文本框文本中第一个单词的每个字符运行循环 此代码在每行上循环,并取第一个单词:
For Each line As String In txtCode.Text.Split(Environment.NewLine)
line = line.Trim().ToLower()
If line.IndexOf(" ") > 0 Then
line = line.Substring(0, line.IndexOf(" ")).Trim()
End If
// do something with 'line' here
Next
Dim strResults As String = String.Empty
For Each strLine As String In IO.File.ReadAllText("C:\Test\StackFlow.txt").Split(ControlChars.NewLine)
Dim lstWords As List(Of String) = strLine.Split(" ").ToList()
If Not lstWords Is Nothing Then
strResults += lstWords(0).ToLower()
If lstWords.Count > 1 Then
For intCursor As Integer = 1 To (lstWords.Count - 1)
strResults += " " & lstWords(intCursor)
Next
End If
End If
Next
当您调用
子字符串时,它将复制字符串的该部分并将其作为新字符串对象返回。因此,即使您成功地更改了返回的子字符串的值,它仍然不会更改Text
属性中的原始字符串
但是,.NET中的字符串是不可变的引用类型,因此当您设置iz=…
时,您所做的只是重新分配iz
变量以指向另一个新的字符串对象。当您设置iz
时,您甚至没有触及它之前指向的复制子字符串的值
要更改文本框的值,必须实际为其text
属性指定一个新字符串值,如下所示:
txtCode.Text = "the new value"
既然如此,我建议使用StringBuilder
对象构建一个新字符串,然后在修改的字符串完成后,将文本框的text
属性设置为该新字符串,例如:
Dim builder As New StringBuilder()
For Each line As String In txtCode.Text.Split({Environment.NewLine}, StringSplitOptions.None)
' Fix case and append line to builder
Next
txtCode.Text = builder.ToString()
循环浏览文本框的每一行,拆分行中的所有单词,确保.ToLower()第一个单词:
For Each line As String In txtCode.Text.Split(Environment.NewLine)
line = line.Trim().ToLower()
If line.IndexOf(" ") > 0 Then
line = line.Substring(0, line.IndexOf(" ")).Trim()
End If
// do something with 'line' here
Next
Dim strResults As String = String.Empty
For Each strLine As String In IO.File.ReadAllText("C:\Test\StackFlow.txt").Split(ControlChars.NewLine)
Dim lstWords As List(Of String) = strLine.Split(" ").ToList()
If Not lstWords Is Nothing Then
strResults += lstWords(0).ToLower()
If lstWords.Count > 1 Then
For intCursor As Integer = 1 To (lstWords.Count - 1)
strResults += " " & lstWords(intCursor)
Next
End If
End If
Next
我用了你们的想法,伙计们,我这样做:
For Each line As String In txtCode.Text.Split(Environment.NewLine)
Dim abc() As String = line.Split(" ")
txtCode.Text = txtCode.Text.Replace(abc(0), LCase(abc(0)))
Next
它是这样工作的。谢谢大家。这里的解决方案很有趣,但它们忽略了.NET的一个基本工具:正则表达式。解决方案可以用一个表达式编写:
(这需要导入System.Text.RegularExpressions
)
此解决方案可能比这里的所有其他解决方案都更高效(它肯定比大多数解决方案更高效),而且它的代码更少,因此出现错误的可能性更小,并且更易于理解和维护。这将只保留最后一行的第一个字。此外,您应该使用abc(0)。ToLower()
而不是旧的VB6样式的LCase
函数。此代码所做的与您想要的完全不同(它取代了给定单词在文本中出现的所有位置),此外还有一些其他缺陷(它效率低下,使用的是Steven在评论中指出的不推荐的方法)打印| | |转到| |打印| | | |这就是我想要的,它是这样工作的。。