程序报argumentoutofrangexception
void comm_DataReceived(object sender, SerialDataReceivedEventArgs e){
int n = comm.BytesToRead;
byte[] buf = new byte[n];
comm.Read(buf, 0, n);//读取缓冲数据
this.Invoke((EventHandler)(delegate
{
//直接按ASCII规则转换成字符串
builder.Append(Encoding.ASCII.GetString(buf, 0, n));
string str_temp = builder.ToString();
string lonStr = null;
string latStr = null;
string sulvStr = null;
string hangxiangStr = null;
string strGPS = null;
int indexOfRMC = str_temp.LastIndexOf("$GPRMC");
strGPS = str_temp.Remove(0, indexOfRMC);
if (indexOfRMC != -1 && strGPS.Length > 10)
{
lonStr = getStrIndex(3, strGPS);//运行到这里报错argumentoutofrangexception,注释掉这个if语句就没事了
latStr = getStrIndex(5, strGPS);
hangxiangStr = getStrIndex(8, strGPS);
sulvStr = getStrIndex(7, strGPS);
builder.Remove(0, builder.Length);
}
textGet.Text += strGPS;
}));
}
private String getStrIndex(int index, String str)
{
String result = null;
char[] str_temp = new char[str.Length];
str_temp = str.ToCharArray();
int sumDot = 0;
int fistDot = 0;
//获得总的逗号数
for (int i = 0; i < str.Length; i++)
{
if (str_temp[i] == ',')
{
sumDot++;
}
//取得第一个逗号所在的序号
if (sumDot == 1)
{
fistDot = i;
}
}
//边界判断,如果给定的逗号序号小于0或者大于逗号总数则退出
if (index < 0 || index > sumDot)
{
result = "0";
}
else
{
//分情况取得相应值
if (index == 0)
{
result = str.Substring(0, fistDot);
}
else if (index == sumDot)
{
int endDot = 0;
for (int i = 0; i < str.Length; i++)
{
int dotTemp = 0;
if (str_temp[i] == ',')
{
dotTemp++;
}
if (sumDot == dotTemp)
{
endDot = i;
}
}
result = str.Substring(endDot + 1, str.Length - endDot);
}
else
{
int p1 = -1; int p2 = -1;
int dotNum = 0;
Char p;
for (int i = 0; i < str.Length; i++)
{
p = str_temp[i];
if (p == ',')
{
dotNum++;
if (dotNum < index)
{
continue;
}
if (p1 == -1)
{
p1 = i + 1;
}
else
{
p2 = i;
break;
}
}
}
result = str.Substring(p1, p2 - p1);
}
}
return result;
}
补充:.NET技术 , C#