2013-04-26 53 views
0

我正在使用Visual Basic.net。在某一行插入字符串

如果我有一個字符串中有很多行,是否可以在某一行插入字符串?我看到有一個字符串插入函數。有沒有函數在另一個字符串的某一行插入一個字符串?

回答

1

字符串不知道「行」是什麼。一個字符串只是一個字符序列。你可以做的是將你的字符串轉換成單行的列表(例如List<string>),然後插入到列表中。

List<string> listOfLines = new List<string>(); 
listOfLines.AddRange(sourceString.Split(new String[] { Environment.NewLine }, StringSplitOptions.None)); 

listOfLines.Insert(13, "I'm new here"); 

string result = String.Join(Environment.NewLine, listOfLines); 

這是C#代碼,但我敢肯定,你可以很容易地將其轉換爲VB.NET。

+0

請參閱添Schmelter的答案:-) – 2013-04-26 11:01:51

+0

我的回答的Visual Basic版本修正了這一點,謝謝! – 2013-04-26 11:10:22

2

有沒有函數在另一個字符串 的某一行插入字符串?

不,因爲字符串不是行列表/數組。您必須將其拆分Environment.NewLine才能獲得陣列,ToList可獲得List(Of String),其中包含Insert method。然後你可以使用String.Join把它在一起,你已經插入後:

Dim lines = MultiLineText.Split({Environment.NewLine}, StringSplitOptions.None).ToList() 
lines.Insert(2, "test") ' will throw an ArgumentOutOfRangeException if there are less than 2 lines ' 
Dim result = String.Join(Environment.NewLine, lines) 
0

沒有一個處理一個字符串作爲線的集合字符串的方法。您可以使用Insert方法,但您必須找出字符串中的哪個位置才能放置該行。

例子:

' Where to insert 
Dim line As Integer = 4 
' What to insert 
Dim content As String = "asdf" 

' Locate the start of the line 
Dim pos As Integer = 0 
Dim breakLen As Integer = Environment.Newline.Length 
For i As Integer = 0 to line 
    pos = text.IndexOf(Environment.Newline, pos + breakLen) 
Next 

' Insert the line 
text = text.Insert(pos, content + Environment.Newline)