簡體   English   中英

字符串包含(子字符串的第二個實例)

[英]String contains (second instance of substring)

我正在嘗試使用C#/ razor操縱一個字符串。

我想要做的只是在“摘要”一詞的第二個外觀右側顯示字符串的一部分。 因此,例如,如果字符串是:

摘要症狀閱讀更多摘要t骨聯盟是青春期后期在足部形成的骨橋。 隨着t骨聯盟從纖維...

我想將其顯示為:

t骨聯盟是青春期后期在足部形成的骨橋。 隨着t骨聯盟從纖維...

所以,我想我需要知道的是你如何使用“contains”來查找字符串中子字符串的第二個實例?

好的...所以Soner讓我朝着正確的方向前進,但是當我嘗試這個時,它會出錯:

@{

string s = @Html.Raw(item.ShortBody);

int firstindex = s.IndexOf("Summary ");
s = s.Remove(0, 8);
int secondindex = s.IndexOf("Summary ");

var strbody = s.Substring(secondindex + 8);
}

@strbody

如何在我的視圖中將操縱的字符串輸出到屏幕? @s不工作..

如果您知道該字符串始終以第一個摘要開頭,則可以在開始搜索之前使用包含偏移量的IndexOf簽名。

 var second = str.IndexOf("Summary", 7);
 var description = str.Substring(second + 8).TrimStart();

或者,您可以找到第一個,然后使用它的位置來找到正確的偏移量

 var second = str.IndexOf("Summary", str.IndexOf("Summary") + 7);
 var description = str.Substring(second + 8).TrimStart();

顯然,這兩者都依賴於字符串確實包含至少兩個單詞Summary實例。 如果不是這種情況,那么在嘗試查找子字符串之前,您需要檢查IndexOf的結果是否等於或大於零。

另一種選擇,如果您知道該單詞最多出現2次是使用LastIndexOf而不是IndexOf ,那么請在此之后獲取子字符串。

 var second = str.LastIndexOf("Summary");
 var description = str.Substring(second + 8).TrimStart();

如果在第二個Summary之后沒有Summary字,則可以使用String.Split方法;

string s = "Summary Symptoms Read More Summary A tarsal coalition is a bridge of bone that forms in the foot in late adolescence. As the tarsal coalition progresses from a fibrous...";
var array = s.Split(new string[] {"Summary "}, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(array[1]);

輸出將是;

A tarsal coalition is a bridge of bone that forms in the foot in late adolescenc
e. As the tarsal coalition progresses from a fibrous...

這是一個demonstration

如果在第二個Summary之后有一個Summary字,則可以使用String.IndexOfString.SubString方法;

string s = "Summary Symptoms Read More Summary A tarsal coalition is a bridge of bone that forms in the foot in late adolescence. As the tarsal coalition progresses from a fibrous...";
int firstindex = s.IndexOf("Summary ");
s = s.Remove(firstindex, 8);
int secondindex = s.IndexOf("Summary ");
Console.WriteLine(s.Substring(secondindex + 8));

輸出將是;

A tarsal coalition is a bridge of bone that forms in the foot in late adolescenc
e. As the tarsal coalition progresses from a fibrous...

這是一個demonstration

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM