String builder问题.... [英] String builder problems....
问题描述
大家好,
我正在尝试使用StringBuilder以奇数格式构造字符串,即
00 00 00 00能够对字符串构建者更精通的人能告诉我我做错了什么。我的代码在
Hi All,
I am trying to use a StringBuilder to construct a string in an odd format ie
"00 00 00 00 " can someone who is a bit more versed with the string builder tell me what I am doing wrong. the code I have is below
string Credit_Value_String = "00000000";
StringBuilder ValueUPDwn = new StringBuilder();
MessageBox.Show("Value is: " + numericUpDown1.Value.ToString());
//if (IsNumeric(numericUpDown1.Value))
// {
for (int i = 0; i <= Credit_Value_String.Length; i+=2)
{
ValueUPDwn.Append(Credit_Value_String.Substring(i,2));
if (i < Credit_Value_String.Length - 2)
{
ValueUPDwn.Append(" ");
}
}
Credit_Value_String = ValueUPDwn.ToString();
MessageBox.Show(Credit_Value_String);
// }
将鼠标悬停在ValueUPDwn上debug正确显示其中的字符串空间00 00 00 00这是想要的(我将在以后使用数值向下工具取值)但是这不会运行长度达到最大值(8 )它试图超越边缘而迷失方向。我不明白的是我之前使用过这种方法没有任何问题......正如我所说的那样,我过去没有使用过StringBuilders,因为我在这里尝试的代码以前在项目中已经工作过了我会后悔的当gremlin稍后爬出来的时候。
Glenn
Hovering over ValueUPDwn in debug shows the string in it space correctly "00 00 00 00" which is what is wanted (I''m going to take the value off a numeric up down tool later) however this does not run the length gets up to max (8) and it tries to go over the edge and gets lost. What I donot understand is I have used this method earlier with no problems...as I said I have not used StringBuilders very much in the past, as the code I am trying here has worked before in the project am I going to regret it when a gremlin crawls out later.
Glenn
推荐答案
我认为你的问题是你在结束时抓住了1个字符。字符串。在下面的函数中,for循环有 Credit_Value_String.length -1 。
如果你的字符串不是偶数个字符,你也会超出字符串长度所以添加:(Credit_Value_String.Length< i + 2)?
I think your problem was the fact that you are grabbing 1 char past the end of the string. In the function below the for loop has Credit_Value_String.length -1.
If your string is not an even number of chars you will also overrun the string length so added: (Credit_Value_String.Length < i+2) ?
static string AnotherCrazyParsingMethod(string Credit_Value_String)
{
StringBuilder ValueUPDwn = new StringBuilder();
for (int i = 0; i < Credit_Value_String.Length; i += 2)
{
ValueUPDwn.AppendFormat("{0}{1} ", Credit_Value_String[i], (Credit_Value_String.Length < i+2) ? '\0' : Credit_Value_String[i + 1]);
}
return ValueUPDwn.ToString();
}
你跑掉了字符串的结尾:
You ran off the end of the string:
for (int i = 0; i <= Credit_Value_String.Length; i+=2)
应该是:
Should be:
for (int i = 0; i < Credit_Value_String.Length; i+=2)
这篇关于String builder问题....的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!