Convert a String to an integer array - arrays

I have an ESP8266 (Arduino) that receives a string (as per the Arduino String class library) of 20 numbers ranging from 0 to 200, comma delimited.
I would like to parse and place the values into an array of integers (e.g. int IntArray[21];. This is what the String looks like:
dataFromClient = "1,2,1,0,1,1,0,1,0,25,125,0,175,100,0,25,175,0,50,125";
I have tried numerous times for the past 2 weeks and I keep getting into "string" hell! Any help would be greatly appreciated.

You should give more details about what you have tried so far.
Since you are using the Arduino libraries you can use the toInt() member function of the string class.
unsigned int data_num = 0;
int data[21];
// loop as long as a comma is found in the string
while(dataFromClient.indexOf(",")!=-1){
// take the substring from the start to the first occurence of a comma, convert it to int and save it in the array
data[ data_num ] = dataFromClient.substring(0,dataFromClient.indexOf(",")).toInt();
data_num++; // increment our data counter
//cut the data string after the first occurence of a comma
dataFromClient = dataFromClient.substring(dataFromClient.indexOf(",")+1);
}
// get the last value out of the string, which as no more commas in it
data[ data_num ] = dataFromClient.toInt();
In this code the string is consumed until only the last value is left in the string. If you want to persist the data in the string you can define a position variable as the substring start point and updating it on every loop cycle to the position after the next comma

Related

Why does my array change its values from the correct ones to random ones when it exits the while loop?

I am trying to take a string of numbers and commas, then separate the numbers from the commas and turn them into ints and store them into an array. I print out the array in the while loop, and it works perfectly fine, but when I try printing the array outside of the while loop it outputs random numbers that change every time. I'm assuming it has something to do with pointers or data storage but I don't know why.
I know that the numbers in the array are correct and ints since I can do mathematical operations to them without resulting in errors, but for some reason as soon as it exits the while loop all the numbers change to random ones.
int commaCount = CntComma(point);
int numArray[commaCount];
//run a while loop to take strings and turn them into ints, then store them in a 1D array
while(point.find(",") != std::string::npos){
int i = 0;
int commaLocate = point.find(",");
string subPart1 = point.substr(0, commaLocate);
numArray[i] = stoi(subPart1);
point = point.substr(commaLocate + 1, (point.length()-1) - subPart1.length());
i++;
}

Correlation value not capturing for custom string as Left Boundary

I am capturing a string as my Left Boundary (LB) and then dividing that LB into 3 parts with strcpy and putting the value in char MyString. When I play my script, the correlation is not getting captured.
char MyString is capturing the value correctly, as when I'm printing it with lr_output_message it is showing me the correct LB as is from the server response values.
This is exactly what I'm doing...
char MyString[9999];
// original LB value is LB=DesktopQueuedActivitiesLV:0:CreateDate\" label=\"Create Date\" value=\"",
for (i = 0 ; i < 1 ; i++) {
lr_save_int(i,"MyRow");
strcpy(MyString, "DesktopQueuedActivitiesLV:");
strcat(MyString, lr_eval_string("{MyRow}"));
strcat(MyString, ":CreateDate\\\" label=\\\"Create Date\\\" value=\\\"");
lr_output_message("MyString = %s",MyString);
web_reg_save_param("DateReceived",
lr_eval_string("LB={MyString}"),
"RB=\">",
"Ord=1",
LAST);
}
Upon replay can't find the value for DateReceived
If I replace the line lr_eval_string("LB={MyString}") with the actual LB value, then it is working. Also, the lr_output_message("MyString = %s",MyString); is printing the exact same original LB value.
Can't figure it out why MyString is capturing the correct value but can't replace during actual line when playing the web_reg_save_param("DateReceived",. Please help.
You are using a loadrunner parameter designation for a C parameter inside of a loop. Both the loadrunner parameter reference is odd here, as is a re-running of the same correlation statement multiple times, as only the last one would have an affect when executed.
lr_output_message("MyString = %s",MyString);
web_reg_save_param("DateReceived",
lr_eval_string("LB={MyString}"),
Notice, the lr_output_message() is treating MyString as a C variable, but the second parameter of the web_reg_save_param() is treating the same element as a LoadRunner parameter. You either need to convert the C string to a LoadRunner parameter, recommend a different name, such as LR_MyString to differentiate the C string from the LR Parameter or create a C parameter which is in the form of "LB=myleftboundary"
lr_output_message("MyString = %s",MyString);
lr_save_string(MyString, "LR_MyString");
web_reg_save_param("DateReceived",
lr_eval_string("LB={LR_MyString}"),
OR
strcpy(MyString, "LB=DesktopQueuedActivitiesLV:");
strcat(MyString, lr_eval_string("{MyRow}"));
strcat(MyString, ":CreateDate\\\" label=\\\"Create Date\\\" value=\\\"");
lr_output_message("MyString = %s",MyString);
web_reg_save_param("DateReceived",
MyString,
You appear to be on the path of creating a psuedo array with DateReceived due to the loop which is executing once in this test, but you are probably wanting to increase the number of loop entries. In this case you are likely to fail for any number of array elements greater than 1 as you will always have the last time executed as the fulfilled correlation.

storing the longest string after strsplit

I am trying to store the longest resultant string after using the function strsplit unable to do so
eg: I have input strings such as
'R.DQDEGNFRRFPTNAVSMSADENSPFDLSNEDGAVYQRD.L'or
'L.TSNKDEEQRELLKAISNLLD'
I need store the string only between the dots (.)
If there is no dot then I want the entire string.
Each string may have zero, one or two dots.
part of the code which I am using:
for i=1:700
x=regexprep(txt(i,1), '\([^\(\)]*\)','');
y=(strsplit(char(x),'.'));
for j=1:3
yValues(1,j)=y{1,j};
end
end
But the string yValues is not storing the value of y, instead showing the following error:
Assignment has more non-singleton rhs dimensions than non-singleton subscripts
What am I doing wrong and are there any suggestions on how to fix it?
The issue is that y is a cell array and each element contains an entire string and it therefore can't be assigned to a single element in a normal array yvalues(1,j).
You need yvalues to be a cell array and then you can assign into it just fine.
yValues{j} = y{j};
Or more simply
% Outside of your loop
yValues = cell(1,3);
% Then inside of your loop
yValues(j) = y(j);
Alternately, if you just want the longest output of strsplit, you can just do something like this.
% Split the string
parts = strsplit(mystring, '.');
% Find the length of each piece and figure out which piece was the longest
[~, ind] = max(cellfun(#numel, parts));
% Grab just the longest part
longest = parts{ind};

How to convert array of strings to string in D?

I have got array of strings like:
string [] foo = ["zxc", "asd", "qwe"];
I need to create string from them. Like:
"zxc", "asd", "qwe" (yes every elements need be quoted and separate with comma from another, but it should be string, but not array of strings.
How can I do it's in functional style?
import std.algorithm, std.array, std.string;
string[] foo = ["zxc", "asd", "qwe"];
string str = foo.map!(a => format(`"%s"`, a)).join(", ");
assert(str == `"zxc", "asd", "qwe"`);
std.algorithm.map takes a lambda which converts an element in the range into something else, and it returns a lazy range where each element is the result of passing an element from the original range to the lambda function. In this case, the lambda takes the input string and creates a new string which has quotes around it, so the result of passing foo to it is a range of strings which have quotes around them.
std.array.join then takes a range and eagerly concatenates each of its elements with the given separator separating each one and returns a new array, and since it's given a range of strings it returns a string. So, by giving it the result of the call to map and ", " for the separator, you get your string made up of the original strings quoted and separated by commas.
std.algorithm.joiner would do the same thing as join, except that it results in a lazy range instead of an array.
Alternatively, use std.string.format
Your format specifier should be something like this:
auto joinedstring = format("%(\“%s\",%)", stringarray)
this is untested as I'm on mobile, but it's something similar to it!

How to get specific parts of a string from an array where every string has a different length?

I have an array of strings, they contain information about objects position in 3D space.The positions are separated with commas. The first one before the comma is x position, second one is y and third one is z. Some of these strings are:
string a = "0.95,2.34,0" string b = "18.05,5,0" string c ="112.1,10,3"
I want to assign 0.95 into float xPos, 2.34 into yPos, 0 into zPos etc.
I want to do these one by one in a for loop for every string in the array.
I couldn't use substr because they have different lengths.
How can i get the substrings between the commas and put them into variables?
-I use c++
P.S sorry for my bad English
Usually there is a Split() type of method in most languages. You would call the method on the incoming string, and split it on the comma then you would have a resulting array with two strings, one of each value. Place the first value in X and the second in Y. You might want a helper method to do this.
You could get the x,y and z string values using RegularExpressions. Then you could use a TryParse method to cast the value to double.

Resources