Hi,
does it exist a class like StringTokenizer (I don't see it in the API) , that parse a string by giving it a special character, or do we need to re create it ?
Thanks
function split(s, sep) {
var tokens = [];
var found = s.find(sep);
while (found != null) {
var token = s.substring(0, found);
tokens.add(token);
s = s.substring(found + sep.length(), s.length());
found = s.find(sep);
}
tokens.add(s);
return tokens;
}
using Toybox.Lang as Lang;
using Toybox.Test as Test;
(:test)
function test_split(logger) {
var dot = ".";
var scenarios = [
{ :s => "", :sep => dot, :expect => [ "" ] },
{ :s => ".", :sep => dot, :expect => [ "", "" ] },
{ :s => ".a", :sep => dot, :expect => [ "", "a" ] },
{ :s => "a", :sep => dot, :expect => [ "a" ] },
{ :s => "a.", :sep => dot, :expect => [ "a", "" ] },
{ :s => "a.b", :sep => dot, :expect => [ "a", "b" ] },
{ :s => "a.b.", :sep => dot, :expect => [ "a", "b", "" ] }
];
var passed = true;
for (var i = 0; i < scenarios.size(); ++i) {
var scenario = scenarios;
var s = scenario[:s];
var sep = scenario[:sep];
var expect = scenario[:expect];
var result = split(s, sep);
// hack around broken Array.equals() failing for arrays with same values
var s1 = result.toString();
var s2 = expect.toString();
// print every assertion we do so we see a summary of what was tested and
// what passes or fails
var message = Lang.format("split($1$, $2$) returned '$3$', expected '$4$'", [ s, sep, result, expect ]);
if (s1.equals(s2)) {
logger.debug(message);
}
else {
logger.error(message);
passed = false;
}
// we could use this, but we get no output if the assert passes and
// if one assertion fails we don't run any more of them.
// hack around assertEqualsMessage(a, b, message) using `a == b'
//Test.assertMessage(
// s1.equals(s2),
// Lang.format("split($1$, $2$) returned '$3$', expected '$4$'", [ s, sep, result, expect ])
//);
}
return passed;
}
[/code]
If you want split() to work with ConnectIQ 1.2, you'd have to either count the separators first and allocate the array, or grow the array as you append.
Travis
function split(s, sep) {
var tokens = []; //This works ? No need for initialisation ? This is good for me, but as I have errors, I asked me if this was not there the problem
var found = s.find(sep);
while (found != null) {
var token = s.substring(0, found);
tokens.add(token);
s = s.substring(found + sep.length(), s.length());
found = s.find(sep);
}
tokens.add(s);
System.println("tokens = "+tokens); //This failed, I don't understand why
return tokens;
}
I'm trying to test your method, but I have issues (it's normal because you don't test it), but I don't understand them
I put so System.println to see what the method do
Sys.println("tokens=" + tokens.toString());