在字符串中插入一个字符(indexof)

ala*_*811 3 vb.net string character

我想要做的是将所需的字符(如“空格”)插入所需的字符串(如“123456789”)的特定点。示例:在字符串 123456789 = 1234 56789 中的位置 5 处插入一个空格。这是我的代码:

    Dim str As String = sum2.Text '123456789
    Dim insStr As String = " " 'space
    Dim strRes As String = str.Insert(5, insStr) '5th position
Run Code Online (Sandbox Code Playgroud)

代码看起来不错,当我使用它或运行它时,我没有收到任何错误,但它不会在第五个位置添加空格,所以我需要一些帮助!

Fab*_*ous 5

您不能认为 startIndexString.Insert(Integer, String)是从零开始的。这意味着如果您打算在第 5 个位置插入空格,则必须将其调整 -1:

Dim insertPosition = 5 ' Assuming this came from the user who says put it in position 5
Dim inStr = " "
Dim strRes = str.Insert(insertPosition - 1, inStr) ' assuming your str already had a value.
Run Code Online (Sandbox Code Playgroud)

这将在 4 和 5 之间插入空格,并产生

1234 56789

我在您的评论中看到您可能想在位置 1、5、7 中插入空格。在这种情况下,您必须反向执行,从最大位置开始到最小位置。这是有原因的假设你想要

_1234_6_89

我使用下划线来表示空格,以便您可以更好地看到它。

在使用之前,请确保您的字符串有足够的字符可供索引索引,否则您将得到一个ArgumentOutOfRangeException.