【发布时间】: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 个空格
-
反对什么?这是一个合法的问题