如何使用 Arduino 中的特定分隔符拆分字符串? [英] How to split a string using a specific delimiter in Arduino?

查看:215
本文介绍了如何使用 Arduino 中的特定分隔符拆分字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串变量,我想提取由 ; 分隔的三个子字符串.到三个字符串变量.

I have a String variable and I want to extract the three substrings separeted by ; to three string variables.

String application_command = "{10,12; 4,5; 2}";

我不能使用子字符串方法,因为这个字符串也可以是以下任何一种或类似的模式.

I cannot use substring method because this string can be like any of the following or similar patterns also.

String application_command = "{10,12,13,9,1; 4,5; 2}"

String application_command = "{7; 1,2,14; 1}"

这些模式中唯一的共同点是由 ; 分隔的三个部分.

The only thing that is common in these patterns is there are three sections separated by ;.

非常感谢任何见解.谢谢

Any insight is much appreciated. Thank you

推荐答案

我认为您需要一个带有自定义分隔符的 split-string-into-string-array 函数.

I think you need a split-string-into-string-array function with a custom separator character.

网络上和 stackoverflow 上已经有几个来源(例如 Split String into String array).

There are already several sources on the web and at stackoverflow (e.g. Split String into String array).

// https://stackoverflow.com/questions/9072320/split-string-into-string-array
String getValue(String data, char separator, int index)
{
  int found = 0;
  int strIndex[] = {0, -1};
  int maxIndex = data.length()-1;

  for(int i=0; i<=maxIndex && found<=index; i++){
    if(data.charAt(i)==separator || i==maxIndex){
        found++;
        strIndex[0] = strIndex[1]+1;
        strIndex[1] = (i == maxIndex) ? i+1 : i;
    }
  }

  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}

你可以使用这个函数如下(用;"作为分隔符):

You can use this function as follows (with ";" as separator):

String part01 = getValue(application_command,';',0);
String part02 = getValue(application_command,';',1);
String part03 = getValue(application_command,';',2);

更正单引号并在示例中添加分号.

correct single quotes and add semicolons in the example.

这篇关于如何使用 Arduino 中的特定分隔符拆分字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆