molo32
1
suppose I have
String s = "BANANA, APPLE, GRAPE"
how to look for the word grape and return me position 2
foo (s, “grape”) // return 2
If I look for the word apple, I should return the position 1
If I look for the word banana, I should return the position 0
1 Like
/**
* Word Index Search (v1.0)
* GoToLoop (2019/Dec/28)
*
* https://Discourse.Processing.org/t/
* search-and-get-position-of-a-word-in-a-comma-separated-string/16671/3
*/
static final String
FRUITS = "BANANA, APPLE, GRAPE",
FRUIT = "GRAPE",
DELIMS = ", ";
void setup() {
final int idx = wordIndexSearch(FRUITS, FRUIT, DELIMS);
println(idx); // 2
exit();
}
static final int wordIndexSearch(
final String words,
final String word,
final String delims) {
if (words == null || word == null || words.isEmpty() || word.isEmpty())
return -1;
if (delims == null || delims.isEmpty())
return int(word.equals(trim(words))) - 1;
int idx = 0;
for (final String w : splitTokens(words, delims))
if (word.equals(w)) return idx;
else ++idx;
return -1;
}
2 Likes
Chrisir
4
same as this
String
FRUITS = "BANANA, APPLE, GRAPE",
FRUIT = "APPLE",
DELIMS = ", ";
void setup() {
size(650, 650);
background(0);
int idx = wordIndexSearch(FRUITS, FRUIT, DELIMS);
println(idx); // result
text(idx, 111, 111);
}//func
// ---------------------------------------------------------------------------
int wordIndexSearch(
String words,
String word,
String delims) {
// validate parameters
if (words == null || word == null || words.isEmpty() || word.isEmpty())
return -1;
if (delims == null || delims.isEmpty())
return int(word.equals(trim(words))) - 1;
// -------
//search
// index
int idx = 0;
for (String w : splitTokens(words, delims)) {
if (word.equals(w)) {
return idx;
}
idx++;
}
// none found
return -1;
}//func
//
1 Like