【问题标题】:How to remove Whitespce from stringArray formed based on whitespace如何从基于空格形成的字符串数组中删除空格
【发布时间】:2014-07-25 08:59:05
【问题描述】:

我有一个包含类似值的字符串。

90  524           000   1234567890       2207 1926    00:34     02:40  S  

现在我已经将这个字符串分解为基于空格的字符串数组。现在我想再创建一个字符串数组,这样所有的空格都被删除并且它只包含真正的值。

我还想根据从删除空格形成的新字符串数组中的选择来从原始字符串数组中获取字符串数组元素的位置。

请帮帮我。

【问题讨论】:

  • 方法 Trim() 会帮助你。
  • 我认为 [this][1] 是您正在寻找的...希望对您有所帮助 [1]:stackoverflow.com/questions/315358/…
  • 嗯比看起来更复杂......你想要什么“职位”?第一个字符的索引?元素的数量,例如第三个?等等等等……如果 524 是第二个和第 5 个和第 7 个和第 10 个元素怎么办?

标签: c# arrays string


【解决方案1】:

您可以通过String.Split 使用StringSplitOptions.RemoveEmptyEntries

var values = input.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);

StringSplitOptions.RemoveEmptyEntries:返回值不包括包含空字符串的数组元素

Split 方法遇到两个连续的空白时,它将返回一个空字符串。使用StringSplitOptions.RemoveEmptyEntries 将删除空字符串并只为您提供所需的值。

您也可以使用LINQ 实现此目的

var values = input.Split().Where(x => x != string.Empty).ToArray();

编辑:如果我理解正确,您想要旧数组中值的位置。如果是这样,您可以通过创建一个字典来做到这一点,其中键是实际值,值是索引:

var oldValues = input.Split(' ');
var values = input.Split().Where(x => x != string.Empty).ToArray();

var indexes = values.ToDictionary(x => x, x => Array.IndexOf(oldValues, x));

然后indexes["1234567890"] 会给你1234567890 在第一个数组中的位置。

【讨论】:

  • OK .Its Working .Other query is how to search the elements of var values for their position into Orginal array with Whitespace with this code..string[] arr= input.Split(' ');
  • @user3816352 你为什么需要那个?你想找到特定项目的索引然后使用 Array.IndexOf 方法
  • 是的,我只想要索引。如何从带有 whitepspace 的数组元素中找到没有空格的数组元素
  • 我会尽快理解你的意思...你能澄清一下吗?一个例子会有帮助
  • 我想要索引,但值将来自没有空格的数组,但索引我想从我从代码string[] arr= input.Split(' ');得到的带有空格的原始数组中获取
【解决方案2】:

你可以使用StringSplitOptions.RemoveEmptyEntries:

string[] arr = str.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);

请注意,我还添加了制表符作为分隔符。还有其他空白字符,如行分隔符,根据需要添加。完整列表here

【讨论】:

    【解决方案3】:
    string s = "90  524           000   1234567890       2207 1926    00:34     02:40  S  ";
    s.Split(' ').Where(x=>!String.IsNullOrWhiteSpace(x))
    

    【讨论】:

    • Split 将创建一个字符串数组。 Where(x=>!String.IsNullOrWhiteSpace(x)) 将删除数组的所有空白或空条目。
    猜你喜欢
    • 2019-05-21
    • 1970-01-01
    • 2021-09-04
    • 2018-05-28
    • 2017-11-20
    相关资源
    最近更新 更多