簡體   English   中英

如何使用String.Replace

[英]How to use String.Replace

快速提問:

我有這個字符串m_Author, m_Editor但是我在字符串中有一些奇怪的ID東西,因此,如果我執行WriteLine ,它將看起來像:

'16; #Luca Hostettler'

我知道我可以執行以下操作:

    string author = m_Author.Replace("16;#", "");
    string editor = m_Editor.Replace("16;#", "");

之后,我將有一個名字,但是我認為將來我還會有其他人和其他ID。

所以問題是:我可以告訴String.Replace("#AndEverythingBeforeThat", "")所以我也可以

'14; #Luca Hostettler'

'15; #Hans Meier'

並得到輸出:Luca Hostettler,Hans Meier,而無需手動將代碼更改為m_Editor.Replace("14;#", ""), m_Editor.Replace("15;#", "") ...?

聽起來您想要一個正則表達式為“至少一個數字,然后是分號和哈希”,並帶有一個“僅在字符串開頭”的錨點:

string author = Regex.Replace(m_Author, @"^\d+;#", "");

或使其更可重用:

private static readonly Regex IdentifierMatcher = new Regex(@"^\d+;#");
...
string author = IdentifierMatcher.Replace(m_Author, "");
string editor = IdentifierMatcher.Repalce(m_Editor, "");

請注意,在以下情況下,可能會有不同的適當解決方案:

  • ID可以是非數字
  • 可能還有其他可忽略的部分,您只需要最后一個哈希值之后的值

您可以使用正則表達式或(我更喜歡) IndexOf + Substring

int indexOfHash = m_Author.IndexOf("#");
if(indexOfHash >= 0)
{
    string author = m_Author.Substring(indexOfHash + 1);
}

要不就,

var author = m_Author.Split('#').Last();

您可以使用string.Split()函數使用#拆分字符串,這將為您提供兩個字符串,首先是#之前的所有內容,然后是#之后的所有內容

使用String.Format

    int number=5;
    string userId = String.Format("{0};#",number)
    string author = m_Author.Replace(userId, "");

如果您只想過濾掉所有不是字母或空格的內容,請嘗試:

var originalName = "#123;Firstname Lastname";
var filteredName = new string(originalName
                                 .Where(c => Char.IsLetter(c) || 
                                             Char.IsWhiteSpace(c))
                                 .ToArray());

該示例將產生Firstname Lastname

List<char> originalName = "15;#Hans Meier".ToList();
string newString = string.Concat(originalName.Where(x => originalName.IndexOf(x) > originalName.IndexOf('#')).ToList());

暫無
暫無

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

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