【发布时间】:2021-03-18 19:14:32
【问题描述】:
我想从最后一个句号中删除所有剩余的字符。我该如何做到这一点?
来自 - “我正在做晚饭。20 年 1 月 12 日。你想加入吗。是/否” To - “我正在做晚饭。20 年 1 月 12 日。你愿意加入吗?”
【问题讨论】:
-
我可以有示例代码吗?
标签: c# html string join character
我想从最后一个句号中删除所有剩余的字符。我该如何做到这一点?
来自 - “我正在做晚饭。20 年 1 月 12 日。你想加入吗。是/否” To - “我正在做晚饭。20 年 1 月 12 日。你愿意加入吗?”
【问题讨论】:
标签: c# html string join character
首先我们可以使用string.Split 和"." 符号。将我们字符串的所有元素分成句子。
string example = "I am making dinner. On 12.01.20. Would you like to join. Yes/No";
// Seperate string into multiple string at the symbol.
List<string> list = example.Split('.').ToList();
完成之后,我们现在可以检查最后一个元素是否包含想要的符号。如果是,我们将其从 List<string> 中删除。
// Remove the last element in our List if it doesn't contain the wanted symbol.
if (!list[list.Count -1].Contains('.')) {
list.RemoveAt(list.Count -1);
}
现在不包含符号的最后一部分已被删除,我们可以将string.Join 和List<string> 合并为一个string。
我们还需要重新添加想要的符号,因为它已被string.Split 剪切。
// Join List into new string and add the wanted symbol after each element in the List.
string concat = string.Join(".", list.ToArray());
【讨论】:
获取从0到.的最后一个索引的子字符串,
var str = "I am making dinner. On 12.01.20. Would you like to join. Yes/No"
var output = str.Substring(0, str.LastIndexOf('.') + 1); //+1 to print Period(.) at the end
Console.WriteLine(output);
【讨论】:
您可以使用LastIndexOf(...) 查找字符最后出现的索引。然后,您可以使用SubString(...) 提取从开头到字符的字符串。
【讨论】: