[英]Not Trimming white spaces from a string in c#
Trim()
Function Not Working Please Help its not trimming the white space. Trim()
函数不起作用请帮助其不要修剪空白。
string samplestring = "172-6573-4955";
string[] array = samplestring .Split('-');
string firstElem = array.First();
string restOfArray = string.Join(" ", array.Skip(1));
array[1] = restOfArray.Trim(); // providing value "6573 4955"
The scenario is I am splitting string and merging 2nd and last index into one but it's merging with white spaces. 场景是我将字符串拆分并将第二个和最后一个索引合并为一个,但它与空白合并。
Trim()
removes whitespace from the front and back of a string, not in the middle. Trim()
删除字符串前面和后面的空格,而不是中间的空格。 The whitespaces in the middle are being inserted by the " "
provided as the parameter to Join()
method. 中间的空格由作为
Join()
方法的参数提供的" "
插入。 You could provide string.empty
instead. 您可以改为提供
string.empty
。
Trim is used to remove all leading and trailing white-space. 修剪用于删除所有前导和尾随空白。 And you want to trim the white space from middle.
您想从中间修剪空白区域。 You may try like this:
您可以这样尝试:
string restOfArray = string.Join("", array.Skip(1));
or better: 或更好:
string restOfArray = string.Join(string.Empty, array.Skip(1));
instead of 代替
string restOfArray = string.Join(" ", array.Skip(1));
Trim is working as expected. 修剪工作正常。 Taken from String.Trim Method :
取自String.Trim方法 :
Removes all leading and trailing white-space characters from the current String object.
从当前String对象中删除所有前导和尾随空格字符。
The possible solutions for you are : 可能的解决方案是:
string restOfArray = string.Join(string.Empty, array.Skip(1));
Or 要么
array[1] = restOfArray.Replace(" ", string.Empty).Trim();
To just split the first n-let from the rest use an additional array or you will end up with spurious data. 要仅将其余的第一个n-let拆分,请使用其他数组,否则您将得到虚假数据。 And join with the correct separator you used in split(
-
): 并加入您在split(
-
)中使用的正确分隔符:
string restOfArray = string.Join("-", array.Skip(1));
string[] result = new string[] { firstElem, restOfArray };
You don't need Trim()
. 您不需要
Trim()
。
You can simplify your code this way: 您可以通过以下方式简化代码:
string[] splitCode(string code)
{
string[] segments;
segments = code.Split('-');
return new string[] { segments.First(), string.Join("-", segments.Skip(1)) };
}
Trim really isn't need here; 这里真的不需要修剪; you can simply split the string and join the parts you want:
您可以简单地拆分字符串并加入所需的部分:
string source = "172-6573-4955";
string[] splitter = new string[] {"-"};
string[] result;
result = source.Split(splitter, StringSplitOptions.None);
string final = (result[1] + result[2]);
Console.Write(final);
Result: 结果:
65734955
Try this: 尝试这个:
string samplestring = "172-6573-4955";
string[] array = samplestring.Split(new char[] {'-'},2);
string result = array[1].Replace("-","");
Also, for your question about randomly putting spaces, can u pls explain "randomly" here. 另外,对于您关于随机放置空格的问题,您能否在这里“随机”解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.