我有一個使用udp發送的字符串。現在我想讀取字符串,將其標記並將其保存到char數組中。只保存每個單詞的第一個字母。所以我只是從元素01到元素05獲得5'e。我在Arduino工作,我知道一些C#,但沒有C或C++。如何將字符串標記保存爲字符變量?
//p_params->packetBuffer contains the following string:
//element01#element02#element03#element04#element05
void packtStriper(receivedPacket * p_params)
{
char delims[] = "#";
char *result = NULL;
int i = 0;
//Tokenize string - 'split' it on hash mark
result = strtok(p_params->packetBuffer, delims);
//Iterate through the tokens and save them to my list
while(result != NULL)
{
p_params->listData[i] = *result;
i++;
result = strtok(NULL, delims);
}
//Display the data just received
for(int j =0; j<i; j++)
{
Serial.print("Data ");
Serial.print(j);
Serial.print(": ");
Serial.println(p_params->listData[j]);
}
}
typedef struct receivedPacket
{
char * REQType;
char * confName;
unsigned int confData[64];
char listData[10];
char packetBuffer[UDP_BUFFER_SIZE];
int packetSize;
int inProduction;
}receivedPacket;
由於下面的代碼打印完整的元素名稱,我認爲我可以使用結果。但是這也會返回一個錯誤。
char str[] = "element01#element02#element03#element04#element05";
char delims[] = "#";
char *result = NULL;
result = strtok(str, delims);
while(result != NULL) {
printf("result is \"%s\"\n", result);
result = strtok(NULL, delims);
}
那麼這段代碼是做你需要的嗎? –
不,它只保存每個單詞的第一個字母到數組 – Bildsoe