首页 > 解决方案 > 在 C89/C90 中解析字符串

问题描述

解析字符串

char* "AS LSLDS SAAL SS"

标签: cstringparsingscanfc89

解决方案


像这样:

int offset;
sscanf(line, "%s %s %d %n", location, direction, &length, &offset);
name = line + offset; // or strncpy or something, if you want a new string instead of just a pointer into the old one

%n记录到目前为止已经消耗了多少字符。如果你向前跳转那么多字符,那么你会得到字符串的其余部分。

旁注:%s在没有最大字段宽度的情况下使用(或让它通过m修饰符自行分配)是危险的,除非你 100% 确定你永远不会得到一个过长的词。


推荐阅读