将字符添加到字符串vb.net
问题描述:
学生姓名的结尾应为“2016”。这是修改字符串的最佳方式:将字符添加到字符串vb.net
Dim Student As String
If Student.Substring(0, 8) = "JoeBlogs" Then
stg = Student.Insert(0, 3)("2016")
End If
我希望字符串读“Joe2016Blogs”做了数千次时,应避免
答
之间,我建议按照Fabio's answer的建议,不过,要回答你的具体问题,你可以做到以下几点:
Dim Student As String = "JoeBlogs"
If Student.Substring(0) = "JoeBlogs" Then
Dim stg as string = Student.Insert(3, "2016")
console.WriteLine(stg)
End If
将会产生如下:
Joe2016Blogs
答
字符串类型是不可变的,所以无论如何你需要创建新的字符串。
可以使用串联
Dim newValue As String = stringVariable + "2016" + anotherStringVariable
,或者您可以使用String.Format
方法
Dim newValue As String = String.Format("{0}2016{1}", firstValue, secondValue);
在VB.NET 14,你可以用更可读的字符串插补功能
Dim newValue As String = $"{first}2016{second}"
如果你创建变量数量未知的循环中的字符串使用StringBuilder
Dim builder As New StringBuilder()
For Each item As String in stringCollection
builder.Append(item)
builder.Append("2016")
End For
Dim allItems As String = builder.ToString()
在你的情况主要问题是分裂“JoeBlog”的名称和“博客”字,然后把“2016”
'学生=学生&“2016”'可缩写为'学生+ =“2016”' – topshot
您的“插入”方法将为您提出的问题完成工作,但它不是在大多数情况下最好的解法比奥的回答给了你几个更好的选择。 – vbnet3d
您的问题的编辑版本没有意义。你说'学生姓名的结尾应该是“2016”,但是你希望“JoeBlogs”改为“Joe2016Blogs”。这里的规则是什么?是否应该在第二个大写字母之前插入“2016”?如果有几个大写字母(例如“JoeFredBlogs”)或没有(例如“joeblogs”)会怎么样? – Blackwood