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

6 回答 6

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

此外,即使您正在搜索一些短语,而不仅仅是一个单词,它也会起作用。

于 2012-11-01T06:18:51.763 回答
4

你可以使用string.EndsWith方法和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);
}
于 2012-11-01T06:38:09.687 回答
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();
   }
}
于 2012-11-01T06:29:54.397 回答
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;
    }
}
于 2012-11-01T06:43:08.950 回答
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;

您也可以对其他文本字符串执行相同操作。

于 2012-11-01T06:27:15.070 回答
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);
        }

    }
于 2012-11-01T06:43:10.523 回答