iv一直在C#中使用此算法来获取给定的字符串,删除任何空格,然后返回结果。是的,有一百万种方法可以做到这一点 但我想让我自己的算法独立于标准类库。而且,我知道有一种方法可以用不同的方式来实现类似的算法,但请在这里裸露在我身边。如果给定字符串中的第一个字符是不是空格我该如何解决这个字符串操作算法?
算法工作正常。 但是,如果有作为第一个字符的空间,返回的字符串包含的字符 正确量,但是,该字符被打印 到控制台。至少当“空白”。我一直盯着这个代码几个小时,尝试这个,试图,但是,对于我的生活,我不能找出什么导致这个问题的 。林吓死 甚至张贴此有人会想出了一个简单的修复,使我看起来迟钝 然后IV细腰大家的时间,但是,四看了又看,这里,那里。我需要帮助! 在代码上挑剔。
public static string RemoveSpaces(string arg)
{
char[] temp = arg.ToCharArray();
int newLength = 0;
//Calculate number of characters that arent spaces.
for (int e = 0; e < temp.Length; e++)
{
if (temp[e] != ' ')//If not a space,
{
newLength++;//then increment number of characters.
}
}
//Now use that number as size in new array
char[] newString = new char[newLength];
//Copy characters that arent spaces to the new char array.
for (uint e = 0, e2 = 0; e < temp.Length; e++, e2++)
{
//NOTE: e2 (and e) is a uint because it can end up negative for a
//short period.
if (temp[0] == ' ')//If the FIRST element is a space
{
e2--;//Then dont let e2 be "truely" incremented in next cycle.
continue;
//e (and e2) will now be incremented by the loop.
//but since we just decremented e2 it will be 1 behind e.
//So we wont be skipping an element in newString if
//we arent going to copy anything to that element.
//Same thing happens in the other if statement below.
//(Where the copying really happens)
}
if (temp[e] != ' ')//If element e is NOT a space,
{
newString[e2] = temp[e];//then copy that element to newString.
}
else//If element e IS a space
{
e2--;//Then dont let e2 be truely incremented in next cycle.
//Cycle is complete so no use for continue; here.
}
}
return new string(newString);//Done!
}
你怎么想达到什么目的?你想删除任何额外的空间尾随和字符内?的 – 2012-02-16 06:03:44
可能重复的[未记录返回时在参数的值是通是从功能](http://stackoverflow.com/questions/9113086/no-records-return-when-the-value-being-pass-in-参数是从功能) – 2012-02-16 06:05:19