替换字符串中的最后一个字符

时间:2012-11-02 12:02:34

标签: vb.net string windows-phone-7

我还有一个关于visual basic的问题,我现在正在开发用于Windows Phone 7.5的应用程序的语言。我的问题是如何替换字符串中的最后一个字符?示例我有字符串“clyde”,现在我想用'o'替换最后一个字符'e',但我该怎么做?任何帮助都会非常感激。

4 个答案:

答案 0 :(得分:3)

String str = "clyde";
str = str.Substring(0, str.Length - 1) + 'o';

尝试了一些在线VB转换器

Dim str As String = "clyde"
str = str.Substring(0, str.Length - 1) & "o"C

答案 1 :(得分:2)

在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

答案 2 :(得分:0)

编辑:现在已经过测试(我忘了添加命名空间

  

myString = Microsoft.VisualBasic.Left(myString,Len(myString) - 1)& myNewChar

示例:

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

答案 3 :(得分:0)

我想出了>>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

用法:

dim s as String= "xxxxx"
msgbox (s.ReplaceFirstChar("y"))
msgbox (s.ReplaceLastchar ("y"))

所以我在任何地方的任何地方都可以简单地重复使用......:)

的问候,
丹尼尔

相关问题