在索引处的其他字符串中插入字符串,即使它不在其中

时间:2015-10-22 14:55:58

标签: vb.net

我想在索引(即20)中在字符串中插入“OK”,即使索引不在字符串中。

例如:

|       INPUT        |           OUTPUT             |
|---------------------------------------------------|
|   "hello world"    |   "hello world         OK"   |
|       "foo"        |   "foo                 OK"   |
| "any large string" |   "any large string    OK"   |

我尝试过使用String.Format ...:

ListBox1.Items.Add(String.Format("hello world{0,20}", "OK"))
ListBox1.Items.Add(String.Format("foo{0,20}", "OK"))
ListBox1.Items.Add(String.Format("any large string{0,20}", "OK"))

...但它与我想要的结果不符。

关于我该怎么做的任何想法?

2 个答案:

答案 0 :(得分:3)

填充第一个字符串,而不是"OK"

ListBox1.Items.Add(String.Format("{0,-20}{1}", "hello world", "OK"))
ListBox1.Items.Add(String.Format("{0,-20}{1}", "foo", "OK"))
ListBox1.Items.Add(String.Format("{0,-20}{1}", "any large string", "OK"))

注意:这将在第一个字符串后添加"OK",即使第一个字符串超过20个字符。

答案 1 :(得分:1)

我觉得这很有效:

Friend Shared Function InsertString(toInsert As String, 
                                    intoString As String, 
                                    atIndex As Integer, 
                                    Optional padChar As Char = " "c) As String

    Return If(atIndex > intoString.Length - 1, 
        intoString & New String(padChar, atIndex - intoString.Length) & toInsert,
        intoString.Insert(atIndex, toInsert))
End Function