簡體   English   中英

如何在字符串中重復的某個特定字符處提取字符串?

[英]How to extract string at a certain character that is repeated within string?

如何從“ MyLibrary.Resources.Images.Properties.Condo.gif”字符串中獲取“ MyLibrary.Resources.Images.Properties”和“ Condo.gif”。

我還需要它能夠處理“ MyLibrary.Resources.Images.Properties.legend.House.gif”之類的內容,並返回“ House.gif”和“ MyLibrary.Resources.Images.Properties.legend”。

IndexOf LastIndexOf無效,因為我需要倒數第二個“。”。 字符。

提前致謝!

更新
到目前為止,感謝您的回答,但是我真的需要它能夠處理不同的名稱空間。 所以,我真正要問的是如何分割字符串中倒數第二個字符?

您可以使用正則表達式或帶'。'的String.Split。 作為分隔符,然后倒數第二個+'。 +最后一塊。

您可以查找IndexOf("MyLibrary.Resources.Images.Properties.") ,將其添加到MyLibrary.Resources.Images.Properties.".Length ,然后從該位置添加.Substring(..)

如果您確切知道要查找的內容,並且可以跟蹤,可以使用string.endswith 就像是

if("MyLibrary.Resources.Images.Properties.Condo.gif".EndsWith("Condo.gif"))

如果不是這種情況,請檢查正則表達式 然后你可以做類似的事情

if(Regex.IsMatch("Condo.gif"))

或更通用的方法:在'。'上分割字符串。 然后獲取數組中的最后兩項。

您可以使用LINQ執行以下操作:

string target = "MyLibrary.Resources.Images.Properties.legend.House.gif";

var elements = target.Split('.');

const int NumberOfFileNameElements = 2;

string fileName = string.Join(
    ".", 
    elements.Skip(elements.Length - NumberOfFileNameElements));

string path = string.Join(
    ".", 
    elements.Take(elements.Length - NumberOfFileNameElements));

這假定文件名部分僅包含一個. 字符,因此要跳過它,您可以跳過剩余元素的數量。

string input = "MyLibrary.Resources.Images.Properties.legend.House.gif";
//if string isn't already validated, make sure there are at least two 
//periods here or you'll error out later on.
int index = input.LastIndexOf('.', input.LastIndexOf('.') - 1);
string first = input.Substring(0, index);
string second = input.Substring(index + 1);

嘗試將字符串拆分成一個數組,並用每個'。'分隔。 字符。

然后,您將獲得類似以下內容的信息:

 {"MyLibrary", "Resources", "Images", "Properties", "legend", "House", "gif"}

然后,您可以采用最后兩個元素。

分解並在char循環中進行操作:

int NthLastIndexOf(string str, char ch, int n)
{
    if (n <= 0) throw new ArgumentException();
    for (int idx = str.Length - 1; idx >= 0; --idx)
        if (str[idx] == ch && --n == 0)
            return idx;

    return -1;
}

這比嘗試使用字符串拆分方法哄騙它便宜,而且代碼也不是很多。

string s = "1.2.3.4.5";
int idx = NthLastIndexOf(s, '.', 3);
string a = s.Substring(0, idx); // "1.2"
string b = s.Substring(idx + 1); // "3.4.5"

暫無
暫無

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

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