【问题标题】:C# string operation [duplicate]C#字符串操作[重复]
【发布时间】:2015-01-25 23:11:00
【问题描述】:

我有一个字符串:

string str = "abc = def; \r\n header \r\n { \r\n def"

在这个字符串中,我想获取字符 { 之前的字符串,即“标题”。

我可以通过

得到{的索引
str.indexOf('{')

但是我们如何才能得到 '{' 之前的字符串呢?

【问题讨论】:

  • 在 Web 或此站点上搜索“C# get string before character”,您会发现很多提示。查看副本。
  • string result = str.SubString(0, str.indexOf('{'));
  • 给定的重复链接给出了指定索引之前的所有字符。我只想要指定 {. 中的前一个字符串
  • 然后你必须定义“就在之前”或“前一个字符串”。如果您可以通过编辑您的问题用文字来解释这一点,那么您已经完成了编写适当代码的一半。是否类似于“以{ 开头的行之前的行(其中'line' 是一个由\r\n 分隔的字符串,忽略所有空格”?您可能还想编写或使用解析器,而不是依赖子字符串,尤其是当多个换行符、其他空格、cmets 和嵌套发挥作用时。
  • @CodeCaster:是的。你的意思是对的。我希望字符“{”之前的字符串忽略所有空格字符。

标签: c# string


【解决方案1】:

在 CodeCaster 评论后编辑

string str = "abc = def; \r\n header \r\n { \r\n def"

int length = str.IndexOf('{'); // if there is no match - the resulted value is -1

string result = (length < 0) ? string.Empty : str.SubString(0, length);

【讨论】:

  • 您能解释一下您的代码是做什么的,以及当输入字符串不包含您要查找的字符时会发生什么?
  • str.SubString(0, length) 会给出整个字符串直到 { 对。我想要 { 之前的字符串。只有一个字符串 i.,在这种情况下为“header”。
  • str.Substring(0, length) 的替代品是str.Remove(length)(因为我们知道str 值的长度至少为1+length)。
猜你喜欢
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
  • 2010-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-15
相关资源
最近更新 更多