我有一个关于使用目标 C 解析字符串的快速问题。目前,我有一个输出 *A_1_2_3_4_~ 的格式。此字符串具有消息开头 (*)、标头 (A)、值 (1) 和消息结尾 (~)。我已经为 arduino 编写了这段代码,但似乎无法让它在目标 c 中正常工作。该函数的作用是将每个值分开并对其进行分类。非常高效和坚固。如果我发送 *A_1_1_1_~,它会识别出 A 代表某物,值为 1、1、1。无论如何,这里的代码:
//protocol for parsing
-(void)protocol:(NSString*)input type:(Boolean*)comType
{
Byte place = 0, index, ID, average, setGet; //any value < 256
int probeType, tempType;
char Header;
NSString *output; //used for parsing
double probeValue, tempValue;
// if(comType){}
// //wire = ""; //reset wire
// else
// analog.text = @"";//serial = ""; //reset serial
//if error in message example: A_1_1_A_1_A_A_A*A_1_1_8.27_1_15.67_3_~
//use '*' as start of message character and grab from *A_1_1_8.27_1_15.67_3_~
probeType = input.length; //get length of string
index = [input rangeOfString:@"*" options:NSBackwardsSearch].location; //index = input.lastIndexOf("*"); //index contains start of message
if(index < 0) //not available or incorrect format
return;
input = [input substringFromIndex:index]; //remove incorrect stuff
average = [input rangeOfString:@"~"].location; //input.indexOf("~", index); //grab end of message
input = [input substringWithRange:NSMakeRange(index+1, average+index)]; //input = input.substring(index + 1, average + 1); //grab valid string only, lower bandwidth
// [self alert: input];
for(Byte i = 0; i < 8; i++) //limit the message length as well
{
// index = [input rangeOfString:@"_"].location; //grab location of
index = [input rangeOfString:@"_" options:Nil range:NSMakeRange(place, input.length)].location;//index = input.indexOf("_", place); //gets first update
// [self alert:index];
if(index < 0 || [input characterAtIndex:index+1] == '~')//input.substring(place, index + 1) == "~") //no '_' found or EOM
break; //two birds one stone
output = [input substringWithRange:NSMakeRange(place, index)];//output = input.substring(place, index); //grab in between
//input = [input stringByReplacingCharactersInRange:NSMakeRange(0, index) withString:@""];//remove already read
switch(i)
{
case 0: //header
Header = [output characterAtIndex:0]; //fast conversion from String to char
break;
case 1: //ID
ID = [output intValue]; //toInt() returns long...not int; perfect for conductivity
break;
case 2: //Probe Type
probeType = [output intValue];
break;
case 3: //Probe Value
probeValue = [output doubleValue];
break;
case 4: //Temperature Type
tempType = [output intValue];
break;
case 5: //Temperature Value
tempValue = [output doubleValue];
break;
case 6: //Average
average = [output intValue];
break;
case 7:
setGet = [output intValue];
break;
}
place = index + 1;
[self alert: output];
}
}