[초보질문] 문자열에서 숫자 문자열 추출

zaru의 이미지

char *str = "X01150Y05810G85X01000Y05810";

가 있을때

X1=01150
Y1=05810
G85
X2=01000
Y2=05810

이렇게 뽑아 내고 싶은데.. strtok 써서 하는데.. 꼬이기만 하고 잘 안되네요..
도움 부탁합니다.

감사합니다.

오호라의 이미지

/* Copy right by MSDN */

#include <string.h>
#include <stdio.h>

char string[] = "X01150Y05810G85X01000Y05810"; /* 타켓 문자열*/
char seps[]   = "ABCDE...........";  /*구분자 */
char *token; 

void main( void )
{
   printf( "%s\n\nTokens:\n", string );
   /* Establish string and get the first token: */
   token = strtok( string, seps );
   while( token != NULL )
   {
      /* While there are tokens in "string" */
      printf( "string : %s\n", token );
      printf( "decimal : %d\n", atoi( token ) );

      /* Get next token: */
      token = strtok( NULL, seps );
   }
}

char seps[]   = "ABCDE...........";  /*구분자 */

이 부분이 간과하기 쉬운 부분입니다. 왜일까요?!~

이유를 아시는 분은 조언 부탁드립니다.

Hello World.

cppig1995의 이미지

저라면 sscanf 를 사용하겠는데.

int X1, X2, Y1, Y2;
char str[2 + 1]. n, m;
sscanf("X01150Y05810G85X01000Y05810",
           "%c%5d%c%5d%c%2s%c%5d%c%5d",
           &n, &X1, &n, &Y1, &m, &Y1, &n, &Y2);
printf("X1=%5d\nY1=%5d\n%c%2s\n"
         "X2=%5d\nY2=%5d",
           X1, Y1, m, str, X2, Y2);

(사실 저도 모르겠어요.)

Real programmers /* don't */ comment their code.
If it was hard to write, it should be /* hard to */ read.

정태영의 이미지

오호라 wrote:
char seps[]   = "ABCDE...........";  /*구분자 */

이 부분이 간과하기 쉬운 부분입니다. 왜일까요?!~

이유를 아시는 분은 조언 부탁드립니다.

그냥 저대로 쓰면 안되고...

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 식으로 써야 되기 때문이 아닌가요 =3=33

strtok 은... 원본 문자열을 변경하기 때문에 사용할때 조심해야 합니다...

오랫동안 꿈을 그리는 사람은 그 꿈을 닮아간다...

http://mytears.org ~(~_~)~
나 한줄기 바람처럼..

sangwoo의 이미지

정태영 wrote:

strtok 은... 원본 문자열을 변경하기 때문에 사용할때 조심해야 합니다...

이런 계열 함수들은 (strtok, strtok_r, strsep) 모두 다 원본을 변화시키더군요. memcpy나 strcpy를 한 뒤에 다루는 것이 아무래도 안전하겠죠.
저는 왠지 저것들 중에 strsep을 주로 쓰는 편이네요. FreeBSD의 strtok 매뉴얼의 영향인듯 합니다.

This interface is obsoleted by strsep(3).

----
Let's shut up and code.

익명 사용자의 이미지

문자열을 파싱하기위한 컴파일러의 원론
컴파일러가 Lex로 Parsing하기위해
Seperator를 문법에서 지정한 문자로 구분
Semantic alnalysis부분에서 의미분석을 통해
구성하는데 이런 패턴을 가지고 펑션이나, 시스템 콜이 운용된다
여기서는 파싱하는 컴파일러 LALR파서가
운용된다는것을 기본전재로 하고 시작해야겟다
우선 파싱하는 방법은 여러가지이다
그것은 알고리즘이 간단할수도 있고, 복잡할수도 있다
Optimization이 된다면 간단해질수있다.
그 알고리즘은 각자가 생각해야겟지만
간단하게 그 제어 루틴 을 알고리즘으로 그려보아야할것이다.
알고리즘 컨트롤 부분이 중요할듯
보인다.

if key words in the string then listen to the following word of that. after that, store and utilize it in another way. process it.
else bite it one by one word.

if no key words then terminate this program.
print some errror message.

스탠다드 함수를 구지 만들어 쓸필요도 없이 사용자가 만들어
써도 무관합니다.
스탠다드 함수는 단순히 Sytem call 이 아닌 Function입니다.
main()함수처럼, 단순히 Function이기에 중요하다고 생각되지
않습니다.

오호라의 이미지

sangwoo wrote:
정태영 wrote:

strtok 은... 원본 문자열을 변경하기 때문에 사용할때 조심해야 합니다...

이런 계열 함수들은 (strtok, strtok_r, strsep) 모두 다 원본을 변화시키더군요. memcpy나 strcpy를 한 뒤에 다루는 것이 아무래도 안전하겠죠.
저는 왠지 저것들 중에 strsep을 주로 쓰는 편이네요. FreeBSD의 strtok 매뉴얼의 영향인듯 합니다.

This interface is obsoleted by strsep(3).

소갑수 wrote:
문자열을 파싱하기위한 컴파일러의 원론
컴파일러가 Lex로 Parsing하기위해
Seperator를 문법에서 지정한 문자로 구분
Semantic alnalysis부분에서 의미분석을 통해
구성하는데 이런 패턴을 가지고 펑션이나, 시스템 콜이 운용된다
여기서는 파싱하는 컴파일러 LALR파서가
운용된다는것을 기본전재로 하고 시작해야겟다
우선 파싱하는 방법은 여러가지이다
그것은 알고리즘이 간단할수도 있고, 복잡할수도 있다
Optimization이 된다면 간단해질수있다.
그 알고리즘은 각자가 생각해야겟지만
간단하게 그 제어 루틴 을 알고리즘으로 그려보아야할것이다.
알고리즘 컨트롤 부분이 중요할듯
보인다.

if key words in the string then listen to the following word of that. after that, store and utilize it in another way. process it.
else bite it one by one word.

if no key words then terminate this program.
print some errror message.

스탠다드 함수를 구지 만들어 쓸필요도 없이 사용자가 만들어
써도 무관합니다.
스탠다드 함수는 단순히 Sytem call 이 아닌 Function입니다.
main()함수처럼, 단순히 Function이기에 중요하다고 생각되지
않습니다.

소스문자열의 변경, 그러므로 카피해서 써야 한다는 것.

LALR Paser이라...파서까지 넘어갈 필요가 있을꺼요?

Lexical Analysis, Scanner만 있어도 충분하겠죠?!

그냥 Seperator를 기준으로 토큰만 나누면 될텐데... ^^;

그리고, 제가 하고 싶은 말은 좀더 다른 얘기인데...

말해버리면 별거 아니지만...

힌트를 드리자면...언어학입니다...앗...

Hello World.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.