【问题标题】:Remove string from the last full stop从最后一个句号中删除字符串
【发布时间】:2021-03-18 19:14:32
【问题描述】:

我想从最后一个句号中删除所有剩余的字符。我该如何做到这一点?

来自 - “我正在做晚饭。20 年 1 月 12 日。你想加入吗。是/否” To - “我正在做晚饭。20 年 1 月 12 日。你愿意加入吗?”

【问题讨论】:

  • 我可以有示例代码吗?

标签: c# html string join character


【解决方案1】:

首先我们可以使用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&lt;string&gt; 中删除。

// 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.JoinList&lt;string&gt; 合并为一个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());

【讨论】:

    【解决方案2】:

    获取从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);
    

    【讨论】:

      【解决方案3】:

      您可以使用LastIndexOf(...) 查找字符最后出现的索引。然后,您可以使用SubString(...) 提取从开头到字符的字符串。

      【讨论】:

      • 你能给我举个例子吗?
      • @Dtorto 1986 我故意省略了一个示例,因为自己实现应该相当简单。如果您难以理解某些特定问题,我可以提供更多详细信息,但链接方法中的文档应该足以解决问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-03
      • 2017-08-19
      • 2013-10-07
      • 2011-01-19
      相关资源
      最近更新 更多