So lets say I have a string called rawinput = "Hi. This is raw input data." and make each word an element in an array. How would I do this assuming I didn't know or tell the program how many words are in the string. Is it possible to do this?
Hello,
sizeof(array)/sizeof(array[0])
Will give you the number of elements in an array. Not sure if that's what you asked ![]()
If you want to know how many words are in a NULL terminated array of chars, you need to first define what a word is. If it is a collection of contiguous letters, separated by spaces. then all you need to do is count the spaces. assuming that only one space is used as a separator. Things get more challenging
if there can
be more than one space
or other kinds
of white space.
you cant have a dynamic array in C you want M for that, nice n easy self sorting sparse arrays, but you wont find an M compatable arduino or similar boards tho.
if its a case of finding out how many nodes of a 2d char array are populated, just ensure the last entry is always a null and count in a loop till null for your answer.
If the OP uses pointers then he can use strlen()
roboticfan101:
So lets say I have a string called rawinput = "Hi. This is raw input data." and make each word an element in an array. How would I do this assuming I didn't know or tell the program how many words are in the string. Is it possible to do this?
yes very well possible,
find below a wordCount sketch, it scans a string and keeps state if it is inside a word or not. You can extend this code to copy the characters to an element of a string array, where the index is defined by the wordcount so far. You can also change the definition of a word
//
// FILE: wordCount.ino
// AUTHOR: Rob Tillaart
// VERSION: 0.1.00
// PURPOSE: demo
// DATE: 2014-11-09
// URL:
//
// Released to the public domain
//
void setup()
{
Serial.begin(115200);
Serial.println("Start ");
Serial.println("Hi. This is raw input data.");
Serial.println(wordCount("Hi. This is raw input data."));
Serial.println("");
Serial.println(wordCount(""));
Serial.println("qwerty");
Serial.println(wordCount("qwerty"));
Serial.println(",./;'[]\\-=");
Serial.println(wordCount(",./;'[]\\-="));
Serial.println("temp\t123\tape");
Serial.println(wordCount("temp\t123\tape"));
Serial.println("temp\t 123\nape");
Serial.println(wordCount("temp\t 123\nape"));
Serial.println("aaa3bbb3");
Serial.println(wordCount("aaa3bbb3"));
}
int wordCount(char* s)
{
int words = 0;
bool inword = false;
for (int i=0; i<strlen(s); i++)
{
switch(s[i])
{
case 'a'...'z':
case 'A'...'Z':
if (inword == false)
{
inword = true;
words++;
}
break;
default:
inword = false;
}
}
return words;
}
void loop() {}
Use the function strtok() to split up your long string.
...R
Things get more challenging
if there canbe more than one space
or other kinds
of white space.
Challenging, aye.