2012-11-01 142 views
3

如果在字符串結尾處有一個字where,我需要修剪字符串。 C#中的快速執行方法是什麼?修整字符串,如果一個字符串以特定單詞結尾

注:修剪這個詞可以是任何東西.. WHERE僅僅是一個例子

string text1 = "My hosue where sun shines"; //RESULT: "My hosue where sun shines" 
string text2 = "My where"; //RESULT: "My" 
string text3 = "My where I WHERE"; //RESULT:"My where I" 

回答

4

可以使用方法和string.Substring

public static string Trim(this string s, string trimmer) 
{ 

    if (String.IsNullOrEmpty(s)|| String.IsNullOrEmpty(trimmer) ||!s.EndsWith(trimmer,StringComparison.OrdinalIgnoreCase)) 
     return s; 
    else 
     return s.Substring(0, s.Length - trimmer.Length); 
} 
4

這是通過擴展方法LINQ變種:

public static string TrimEnd(this string s, string trimmer) 
{ 
    //reverse the original string we are trimmimng 
    string reversed = string.Concat(s.Reverse()); 
    //1. reverse the trimmer (string we are searching for) 
    //2. in the Where clause choose only characters which are not equal in two strings on the i position 
    //3. if any such character found, we decide that the original string doesn't contain the trimmer in the end 
    if (trimmer.Reverse().Where((c, i) => reversed[i] != c).Any()) 
     return s; //so, we return the original string 
    else //otherwise we return the substring 
     return s.Substring(0, s.Length - trimmer.Length); 
} 

,並使用它:

string text1 = "My hosue where sun shines"; 
string text2 = "My where"; 
string text3 = "My where I WHERE"; 
Console.WriteLine(text1.TrimEnd("where")); 
Console.WriteLine(text2.TrimEnd("where")); 
Console.WriteLine(text3.TrimEnd("WHERE")); 
Console.ReadLine(); 

區分大小寫。爲了使其不區分大小寫,您需要在擴展方法爲低或高的情況下使strimmer

此外,即使您正在搜索一些詞組,而不是隻搜索一個詞,它也可以工作。

+0

謝謝......爲了別人的利益,你還可以用簡單的英語解釋邏輯嗎? (就像什麼是檢查條件) – Lijo

+0

@Lijo當然,我會在一分鐘內編輯我的帖子 – horgh

0

首先將字符串拆分爲一個數組,然後檢查最後一個數組元素,並用數組元素本身替換該字符串。

string[] words1 = text1.Split(' '); 
string replaced_string = ""; 
if words1[words1.length-1]=='where' 
for (int i = 0; i < length-2; i++) 
{ 
     replaced_string + words1[i] + " "; 
} 
replaced_string.TrimEnd(); 
text1 = replaced_string; 

您可以爲其他文本字符串做同樣也是如此。

2

你可以用正則表達式做到這一點:

Regex.Replace(s, @"(\A|\s+)where\s*\Z", "", RegexOptions.IgnoreCase).Trim(); 

用法:

"My hosue where sun shines".TrimWhere() // "My hosue where sun shines" 
"My where".TrimWhere()     // "My" 
"My where I WHERE".TrimWhere()   // "My where I" 
"".TrimWhere()       // "" 
"My blahWHERE".TrimWhere()    // "My blahWHERE" 
"Where".TrimWhere()      // "" 

對於此示例中,我創建了擴展方法(添加System.Text.RegularExpressions命名空間)

public static class StringExtensions 
{ 
    public static string TrimWhere(this string s) 
    { 
     if (String.IsNullOrEmpty(s)) 
      return s; 

     return Regex.Replace(s, @"(\A|\s+)where\s*\Z", "", RegexOptions.IgnoreCase) 
        .Trim(); 
    } 
} 
+1

這是否修剪它的案件「blablaWHERE」? – mostruash

+1

@mostruash謝謝,很好的捕獲 - 我已經添加了'\ s +'模式 –

+2

此外,如果單個單詞'where'也應該被修剪,你需要pattern'(\ A | \ s +)\ where \ s * \ Z' –

1

使用的情況下,鈍感EndsWith方法調用,以確定您的字符串,你要修剪的字符結束,如果它從字符串的結尾去掉修剪字符串的字符數。

在方法中可能是這樣的:

private string MyTrimEnd(string s, string trimString) { 
    if (s.EndsWith(trimString, StringComparison.OrdinalIgnoreCase)) { 
     // A case-insenstive check shows the string ends with the trimString so remove from the 
     // end of the string the number of characters in the trimString. 
     // Trim the result to leave no trailing space characters, if required. 
     return s.Remove(s.Length - trimString.Length).Trim(); 
    } else { 
     // The check showed the passed string does not end with the trimString so just return the 
     // passed string. 
     return s; 
    } 
} 

檢測方法與結果:

Console.WriteLine("'{0}'", MyTrimEnd(text1, "where"));  // 'My hosue where sun shines' 
Console.WriteLine("'{0}'", MyTrimEnd(text2, "where"));  // 'My' 
Console.WriteLine("'{0}'", MyTrimEnd(text3, "where"));  // 'My where I' 
Console.WriteLine("'{0}'", MyTrimEnd("WHERE", "where")); // '' 
Console.WriteLine("'{0}'", MyTrimEnd("WHE", "where"));  // 'WHE' 
Console.WriteLine("'{0}'", MyTrimEnd("blablaWHERE", "where")); //'blabla' 
Console.WriteLine("'{0}'", MyTrimEnd(string.Empty, "where")); //'' 
Console.WriteLine("'{0}'", MyTrimEnd("WHEREwherE", "where")); //'WHERE' 

或者作爲一個擴展的方法:

public static string MyTrimEnd(this string s, string trimString) { 
    if (s.EndsWith(trimString, StringComparison.OrdinalIgnoreCase)) { 
     return s.Remove(s.Length - trimString.Length).Trim(); 
    } else { 
     return s; 
    } 
} 
+0

+1對我感到羞恥,我完全忘記了'EndsWith' – horgh

0

@Konstantin Vasilcov的另一個版本答案是

public static string MyTrim1(string commandText, string trimmer) 
    { 

     if (String.IsNullOrEmpty(commandText) || String.IsNullOrEmpty(trimmer)) 
     { 
      return commandText; 
     } 

     string reversedCommand = (string.Concat(commandText.Reverse())).ToUpper(); 
     trimmer = trimmer.ToUpper(); 

     if (trimmer.Reverse().Where((currentChar, i) => reversedCommand[i] != currentChar).Any()) 
     { 
      return commandText; 
     } 

     else 
     { 
      return commandText.Substring(0, commandText.Length - trimmer.Length); 
     } 

    } 
相關問題