C> Comma-delimited string itemization> Implementation of extractCsvRow ()

Operating environment


Embedded C(MSP430)

I implemented extractCsvRow () which extracts each item from the comma-separated string in a situation like strcpy ().

code v0.1

http://ideone.com/AmrfcF

sample.c


#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

/*
v0.1 2016/05/25
  - add extractCsvRow()
*/

static const char *s_rcvd = "pval,3.141,2.718,6.022"; // dummy data

static bool extractCsvRow(char *srcPtr, int length, int itmidx, char *dstPtr)
{
	char szbuf[20];
	int pos = 0;
	int cntComma = 0;
	
	int idx;
	if (dstPtr == NULL) {
		return false;
	}
	
	for(idx=0; idx < length; idx++) {
		if (srcPtr[idx] == ',') {
			if (cntComma == itmidx) {
				szbuf[pos++] = 0x00;
				strcpy(dstPtr, szbuf);
				return true;
			}
			cntComma++;
		} else {
			if (cntComma == itmidx) {
				szbuf[pos++] = srcPtr[idx];
			}
		}
	}
	
	if (cntComma == itmidx) {
		szbuf[pos++] = 0x00;
		strcpy(dstPtr, szbuf);
		return true;
	}

	return false;
}	

int main(void) {
	bool res;
	static char szbuf[20];
	int idx;
	
	for(idx=0; idx < 4; idx++) {
		memset(szbuf, 0, sizeof(szbuf));
		res = extractCsvRow(s_rcvd, strlen(s_rcvd), idx, szbuf);
		if (res) {
			printf("%s\n", szbuf);
		}
	}

	return 0;
}

result

result


pval
3.141
2.718
6.022

It's working, but it may need a little more review.

You can make it even easier if you do it with Arduino etc. http://qiita.com/7of9/items/ac7737c17c4dacf09bc3

For Unity http://qiita.com/7of9/items/f6ff497333bf558a5951

Recommended Posts

C> Comma-delimited string itemization> Implementation of extractCsvRow ()
implementation of c / c ++> RingBuffer (N margins)
Implementation of Fibonacci sequence
Summary of string operations