【问题标题】:Find the last character of a string that got whitespaces after it查找后面有空格的字符串的最后一个字符
【发布时间】:2017-08-02 14:40:31
【问题描述】:

这听起来可能很愚蠢,但是如果字符串看起来像这样"string with white-space after last character ",我怎么能找到字符串中的最后一个字符索引,如果它是一致的并且只有 1 没问题,但有时它可能是 2 或 3 白色-空格

编辑: 我无法将当前字符串修剪为新字符串,因为最后一个字符的索引不正确。我想保持字符串原样

这就是我得到的原因和结果

string description = "Lorem Ipsum is simply dummy text of the printing and typesetting indu. Lorem Ipsum has ben indusry s tandard dummy text ever since the 1500s.";
description = Regex.Replace(description, @"(?></?\w+)(?>(?:[^>'""]+|'[^']*'|""[^""]*"")*)>", String.Empty);
if (description.Count() > 101)
{
    description = description.Substring(0, 101);
    if (description.GetLast() != " ")
    {                    
        description = description.Substring(0, description.LastIndexOf(" ", 101)) + "...";
    }
    else
    {
        //here is should find the last character no mather how many whitespaces
        description = description.Substring(0, description.Length - 1) + "...";
    }
}

【问题讨论】:

  • 你说你不能修剪字符串 - 你知道 Trim() 实际上并没有修改原始字符串而是返回一个新字符串吗?
  • 好吧,你这里还有更多问题。如果你最终得到的字符串不包含空格(或制表符),你最终会得到 LastIndexOf(" ") 返回 -1 并崩溃。 TrimEnd() 就像人们建议的那样,如果使用 LastIndexOf(); 则检查 -1;
  • 首先是什么问题?您想要前 100 个字符而不中断最后一个单词?
  • 我需要得到 101 个字符,它们需要按原样写。所以..“字符串可能看起来像这样,在这之后有 5 个空格”,我无法修剪并得到一个看起来像“stringmightlooklikethis”的描述。我处理不插入单词的问题,但有时在最后一个字符之后只是超过 1 个空格
  • 反对什么?这是一个合法的问题

标签: c# regex string


【解决方案1】:

为了完整起见,这里有一个使用正则表达式的解决方案(我并不是说它比其他建议的解决方案更好):

var text = "string with whitespace after last character  ";
var regex = new Regex(@"\s*$");
var match = regex.Match(text);
var lastIndex = match.Index - 1;

请注意,如果字符串为空,lastIndex 将为 -1,您需要在代码中进行处理。

【讨论】:

    【解决方案2】:

    这里的所有答案都是 trim 字符串,所以创建一个带有 shifted 索引的新字符串,因此最终结果将是 wrong 索引原始字符串。

    相反,会做的只是

    "string with whitespace after last character ".ToCharArray().
              Select((x,i)=> new {x,i}).Where(ch=>ch.x != ' ').Last();
    

    返回:

    x :    'r'
    index: 42
    

    【讨论】:

    • 那(即“这里的所有答案都是修剪......所以最终结果将是错误的索引”)仅适用于字符串开头也有空格的情况以及 最后。 OP没有指定是否可以,但至少亚历克斯在他的回答中明确提到了这个前提条件;并且 AndrewR 使用的 TrimEnd 根本没有您描述的问题。
    • @nyarlathotep: 看看OP提供的例子,末尾有个空格。
    • 最后,是的,但是为什么修剪后会有错误的索引?修剪后的字符串包含原始字符串末尾没有空格,因此修剪后的字符串-1的长度原始字符串中最后一个字符的索引!
    • @nyarlathotep: 如果末尾有空格,则没有效果,但如果字符串前面有空格,则有。
    【解决方案3】:

    试试这个:

            string s = "string with whitespace after last character    ";
            int index = s.Length - s
                .ToCharArray()
                .Reverse()
                .TakeWhile(c => c == ' ')
                .Count();
    

    【讨论】:

    • 你不需要.ToCharArray(),因为你可以直接在字符串s上使用Linq(string实现IEnumerable&lt;char&gt;)。
    【解决方案4】:

    如果字符串在第一个字符之前没有任何空格,yourString.Trim().Length -1 应该完成这个。

    【讨论】:

      【解决方案5】:

      使用 trim 函数并获取该字符串的最后一个索引..

      【讨论】:

        【解决方案6】:

        为什么不修剪你的字符串

        string abc = "string with whitespace after last character ";
        abc = abc.trim();
        

        希望对你有帮助

        【讨论】:

          【解决方案7】:

          也许是这个?

          String s = "string with whitespace after last character  ";
          int lastCharIndex = s.Length - (s.TrimEnd().Length);
          

          【讨论】:

            【解决方案8】:

            就这个。不需要 Linq 或 Regex。但是TrimEnd(),不是Trim(),而且你不需要考虑字符串开头是否有空格。

            string s = "string with whitespace after last character  ";
            int lastCharIndex = s.TrimEnd().Length - 1;
            

            如果 OP 真的想为此使用正则表达式,那么这是我的即兴创作:

                    string text = "string with whitespace after last character  ";
                    Match m = Regex.Match(text, @"^(.*)(\w{1})\s*$");
                    if (m.Success)
                    {
                        int index = m.Groups[1].Length;
                        Console.WriteLine(text[index]);
                        Console.WriteLine(index);
                    }
            
                    Console.ReadLine();
            

            【讨论】:

              【解决方案9】:

              使用Array.FindLastIndex 搜索不等于空格的最后一个字符:

              Array.FindLastIndex(str.ToCharArray(), ch =&gt; !Char.IsWhiteSpace(ch))

              【讨论】:

                【解决方案10】:

                假设末尾的其他whitespace characters(例如制表符或换行符)也被忽略并不重要,只需使用修剪:

                String s = "string with whitespace after last character  ";
                int lastChar = s.TrimEnd().Length-1;
                

                请注意,原始字符串 s 保持不变(请参阅 TrimEnd() documentation)。

                【讨论】:

                • 即使我在字符串的开头有空格也能正常工作。除了-1。对我来说,它只是找到s.TrimEnd();
                • @Maciej:是的,感谢您的提示,我最初的解决方案不适用于前导空格,现在使用 TrimEnd 可以。我会赞成你的答案,但它有同样的问题;)
                • 我会对投反对票的原因感兴趣...我的回答有什么问题吗?
                猜你喜欢
                • 2014-09-19
                • 1970-01-01
                • 2022-06-25
                • 1970-01-01
                • 2021-10-14
                • 2012-01-16
                • 1970-01-01
                • 1970-01-01
                • 2017-10-30
                相关资源
                最近更新 更多