0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C > カンマ区切り文字列の項目分割 > extractCsvRow()の実装

Last updated at Posted at 2016-05-25
動作環境
組込みC (MSP430)

strcpy()くらいある状況でカンマ区切り文字列から各項目を取出すextractCsvRow()を実装してみた。

code v0.1

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;
}

結果

結果
pval
3.141
2.718
6.022

一応動いているが、もう少し見直しが必要かもしれない。

Arduinoなどでやるともっと楽ができる http://qiita.com/7of9/items/ac7737c17c4dacf09bc3

Unityなら http://qiita.com/7of9/items/f6ff497333bf558a5951

0
1
9

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?