Skip to content

Commit 31c1592

Browse files
authored
add Stream::readStringUntil function that uses string terminator (#9011)
* add readStringUntil function with string terminator * rename count parameter to untilTotalNumberOfOccurrences
1 parent fb8d6d6 commit 31c1592

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

cores/esp8266/Stream.cpp

+26
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,32 @@ String Stream::readStringUntil(char terminator) {
262262
return ret;
263263
}
264264

265+
String Stream::readStringUntil(const char* terminator, uint32_t untilTotalNumberOfOccurrences) {
266+
String ret;
267+
int c;
268+
uint32_t occurrences = 0;
269+
size_t termLen = strlen(terminator);
270+
size_t termIndex = 0;
271+
size_t index = 0;
272+
273+
while ((c = timedRead()) > 0) {
274+
ret += (char) c;
275+
index++;
276+
277+
if (terminator[termIndex] == c) {
278+
if (++termIndex == termLen && ++occurrences == untilTotalNumberOfOccurrences) {
279+
// don't include terminator in returned string
280+
ret.remove(index - termIndex, termLen);
281+
break;
282+
}
283+
} else {
284+
termIndex = 0;
285+
}
286+
}
287+
288+
return ret;
289+
}
290+
265291
// read what can be read, immediate exit on unavailable data
266292
// prototype similar to Arduino's `int Client::read(buf, len)`
267293
int Stream::read (uint8_t* buffer, size_t maxLen)

cores/esp8266/Stream.h

+1
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ class Stream: public Print {
115115
// Arduino String functions to be added here
116116
virtual String readString();
117117
String readStringUntil(char terminator);
118+
String readStringUntil(const char* terminator, uint32_t untilTotalNumberOfOccurrences = 1);
118119

119120
virtual int read (uint8_t* buffer, size_t len);
120121
int read (char* buffer, size_t len) { return read((uint8_t*)buffer, len); }

0 commit comments

Comments
 (0)