【问题标题】:Get String Between 2 Strings with Arduino使用 Arduino 获取 2 个字符串之间的字符串
【发布时间】:2016-11-04 14:52:01
【问题描述】:

我正在寻找一种使用 Arduino 在 2 个字符串之间获取字符串的方法。这是源字符串:

Hello, my name is John Doe# and my favourite number is 32#.

输出必须是:

String name = "John Doe"; //Between "name is " and "#"
String favouriteNumber = "32"; //Between "number is " and "#"

如何使用 Arduino 实现这一点?

我无法在网上找到任何有关此的信息。 C 的那些示例无论如何都不起作用。我知道在 Arduino 中不建议使用 String,但我必须这样做以使事情变得更简单。

顺便说一句,这种使用“#”表示数据结束的方法并不是一种理想的方法,因为我希望输入更易于阅读和更自然。 是否有人也可以建议另一种方法来做到这一点?

提前致谢!

【问题讨论】:

  • >but I have to do it this way to make things simpler. 这是你的错误:在 Arduino C 中,char*strings 更强大。

标签: string arduino


【解决方案1】:

函数 midString 查找位于其他两个字符串“start”和“finish”之间的子字符串。如果这样的字符串不存在,则返回“”。还包括一个测试代码。

void setup() {
  test();
}

void loop() {
  delay(100);
}

String midString(String str, String start, String finish){
  int locStart = str.indexOf(start);
  if (locStart==-1) return "";
  locStart += start.length();
  int locFinish = str.indexOf(finish, locStart);
  if (locFinish==-1) return "";
  return str.substring(locStart, locFinish);
}

void test(){
  Serial.begin(115200);
  String str = "Get a substring of a String. The starting index is inclusive (the corresponding character is included in the substring), but the optional ending index is exclusive";
  Serial.print(">");
  Serial.print( midString( str, "substring", "String" ) );
  Serial.println("<");
  Serial.print(">");
  Serial.print( midString( str, "substring", "." ) );
  Serial.println("<");
  Serial.print(">");
  Serial.print( midString( str, "corresponding", "inclusive" ) );
  Serial.println("<");
  Serial.print(">");
  Serial.print( midString( str, "object", "inclusive" ) );
  Serial.println("<");
 }

【讨论】:

    【解决方案2】:

    刚刚搜索了这个,没有看到答案,所以我做了一个。 由于代码的可读性和简单性,我也更喜欢使用 String。 对我来说,这比从我的 arduino 中榨出每一滴果汁更重要。

    String name = GetStringBetweenStrings("Hello, my name is John Doe# and my favourite number is 32#." ,"name is ","#");
    
    
    
    String GetStringBetweenStrings(String input, String firstdel, String enddel){
          int posfrom = input.indexOf(firstdel) + firstdel.length();
          int posto   = input.indexOf(enddel);
          return input.substring(posfrom, posto);
    }
    

    注意第一种情况很好,但对于第二种情况,您必须将第二个过滤器字符串更改为“#”。所以它不使用第一次出现的#

    【讨论】:

    • 如果所需的子字符串不存在,此代码将返回不正确的字符串。如果两端的两个字符串相同,它也不起作用。
    猜你喜欢
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 2012-12-28
    相关资源
    最近更新 更多