vb.net 替换字符串中的最后一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13194860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
replacing the last character in a string
提问by clydewinux
I have another question again about visual basic, the language I am using now in developing apps for windows phone 7.5. My question is how can I replace the last character in a string? Example I have the string "clyde", now I want to replace the last character 'e' with 'o', but how can I do that? Any help would be so appreciated.
我还有另一个关于visual basic的问题,我现在在为windows phone 7.5开发应用程序时使用的语言。我的问题是如何替换字符串中的最后一个字符?示例 我有字符串“clyde”,现在我想用 'o' 替换最后一个字符 'e',但是我该怎么做呢?任何帮助将不胜感激。
回答by nkchandra
String str = "clyde";
str = str.Substring(0, str.Length - 1) + 'o';
Tried some online VB converter
尝试了一些在线VB转换器
Dim str As String = "clyde"
str = str.Substring(0, str.Length - 1) & "o"C
回答by RoelF
in vb.net script:
在 vb.net 脚本中:
Dim s As String
Sub Main()
s = "hello world"
s = s.Substring(0, s.Length - 1) & "o"
Console.WriteLine(s)
Console.ReadLine()
End Sub
回答by Luke94
EDIT: now tested (I forgot to add the namespace
编辑:现在测试(我忘了添加命名空间
myString = Microsoft.VisualBasic.Left(myString, Len(myString) - 1) & myNewChar
myString = Microsoft.VisualBasic.Left(myString, Len(myString) - 1) & myNewChar
example:
例子:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load Dim myString As String Dim myChar As String myString = "clyde" myChar = "o" myString = Microsoft.VisualBasic.Left(myString, Len(myString) - 1) & myChar MsgBox(myString) End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load Dim myString As String Dim myChar As String myString = "clyde" myChar = "o" myString = Microsoft.VisualBasic.Left(myString, Len(myString) - 1) & myChar MsgBox(myString) End Sub
回答by dba
I came up with an Extension of the String Class as described >>on CodeProject<<.
我想出了一个字符串类的扩展,如>>on CodeProject<< 所述。
Imports Microsoft.VisualBasic
Imports System.Runtime.CompilerServices
Public Module StringExtensions
<Extension()> _
Public Function ReplaceFirstChar(str As String, ReplaceBy As String) As String
Return ReplaceBy & str.Substring(1)
End Function
<Extension()> _
Public Function ReplaceLastChar(str As String, ReplaceBy As String) As String
Return str.Substring(0, str.Length - 1) & ReplaceBy
End Function
End Module
Usage:
用法:
dim s as String= "xxxxx"
msgbox (s.ReplaceFirstChar("y"))
msgbox (s.ReplaceLastchar ("y"))
So I have a simple reuse in my Assembly anywhere... :)
所以我在我的大会中的任何地方都有一个简单的重用...... :)
Regards,
Daniel
问候,
丹尼尔

