【发布时间】:2015-03-14 19:51:22
【问题描述】:
我在 Processing 中构建了一个程序,它可以伪随机地生成命令式句子。该程序结合了随机选择的动词、所有格形容词和名词,以显示最后一个句子。 这是该程序的摘要版本:
void sentence() {
String VerbList = "abide accelerate accept accomplish achieve acquire acted etc.”;
String[] Verbs = VerbList.split("\\s");
String PossessiveAdjectiveList = "my your his her its our their";
String [] PossessiveAdjectives = PossessiveAdjectiveList.split("\\s");
String NounList = "account achiever acoustics act action activity actor etc.”;
String[] Nouns = NounList.split("\\s");
int verb = int(random(Verbs.length));
int possessiveAdjective = int(random(PossessiveAdjectives.length));
int noun = int(random(Nouns.length));
String Sentence = Verbs[verb]+" "+PossessiveAdjectives[possessiveAdjective]+" "+Nouns[noun];
println(Sentence);
将代码移至 Arduino IDE 后,我立即发现缺少 string.split 函数。我知道我可以使用 strtok 将字符串转换为标记;但是,我不确定如何通过随机生成的整数来选择单个标记。我应该尝试使用 strtok 吗?到目前为止,这是我的代码:
#include <Wire.h>
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
#define WHITE 0x7
void setup() {
Serial.begin(9600);
lcd.setBacklight(WHITE);
lcd.begin(16, 2);
lcd.setCursor(0, 0);
sentence();
}
void sentence() {
char VerbList[] = "abide accelerate accept accomplish achieve acquire acted etc.";
char* Verbs = strtok(VerbList, " ");
char PossessiveAdjectiveList[] = "my your his her its our their";
char* PossessiveAdjectives = strtok(PossessiveAdjectiveList, " ");
char NounList[] = "account achiever acoustics act action activity actor etc.";
char* Nouns = strtok(NounList, " ");
//int verb = int(random(Verbs.length));
//int verb = Verbs.substring(random(Verbs.length));
//int possessiveAdjective = int(random(PossessiveAdjectives.length));
//int noun = int(random(Nouns.length));
//String Sentence = Verbs[verb]+" "+PossessiveAdjectives[possessiveAdjective]+" "+Nouns[noun];
//lcd.print(Sentence);
}
uint8_t i=0;
void loop() {
uint8_t buttons = lcd.readButtons();
if (buttons) {
lcd.clear();
lcd.setCursor(0,0);
if (buttons & BUTTON_SELECT) {
sentence();
}
}
}
【问题讨论】:
标签: string split arduino token strtok