2012-05-16 55 views
0

如何從「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不起作用,因爲我需要倒數第二個'。'字符。

在此先感謝!

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

回答

1

您可以使用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)); 

這假定該文件名部分僅包含一個.字符,所以要得到它,你跳過其餘元素的數量。

1

您可以使用正則表達式或String.Split與'。'作爲分隔符並返回倒數第二個+'。' +最後一塊。

1

你可以找IndexOf("MyLibrary.Resources.Images.Properties."),從該位置

1

添加到MyLibrary.Resources.Images.Properties.".Length然後.Substring(..)如果你知道你在尋找什麼,它的尾部,你可以使用string.endswith。類似於

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

如果不是這種情況,請檢查regular expressions。然後你可以做類似於

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

或者更通用的方法:將字符串拆分爲'。'。然後抓住數組中的最後兩項。

1
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); 
1

嘗試將字符串拆分爲一個數組,每個'。'分隔開來。字符。

你會再有這樣的事情:

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

然後,您可以採取的最後兩個元素。

1

就壞了,做它在字符循環:

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" 
相關問題