strtok() 对于解析句点但保留句点有用吗? (C)
Would strtok() be useful for parsing out periods but keeping them? (C)
我正在尝试删除由多个句子组成的字符串中的所有空格,但我还想将句点与每个标记分开。 strtok() 是否仍然对此有用,或者还有其他我应该知道的功能吗?
char str[] ="- This. is a s.ample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,-"); //any other tokens you want to use here
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,-");
}
如果您想知道句点在哪里,并将它们视为单独的标记,那么 strtok()
不是正确的函数。它用空值分隔分隔符;您不会被告知它找到了哪个定界符。
您可能需要查看:
您还可以查看有关 strtok()
及其替代方案的其他问题。有许多。 strtok()
is a dangerous function. You can't afford to use in a function called from another function that is also using strtok()
, nor can you afford to call any other function that uses strtok()
. You should look up POSIX strtok_r()
or Microsoft's strtok_s()
;它们可以安全地用于库函数。您还可以查找 strsep()
.
您可能会发现以下问题之一很有用:
- Need to know when no data appears between two token separators
还有很多其他人可以提供帮助。
我正在尝试删除由多个句子组成的字符串中的所有空格,但我还想将句点与每个标记分开。 strtok() 是否仍然对此有用,或者还有其他我应该知道的功能吗?
char str[] ="- This. is a s.ample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,-"); //any other tokens you want to use here
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,-");
}
如果您想知道句点在哪里,并将它们视为单独的标记,那么 strtok()
不是正确的函数。它用空值分隔分隔符;您不会被告知它找到了哪个定界符。
您可能需要查看:
您还可以查看有关 strtok()
及其替代方案的其他问题。有许多。 strtok()
is a dangerous function. You can't afford to use in a function called from another function that is also using strtok()
, nor can you afford to call any other function that uses strtok()
. You should look up POSIX strtok_r()
or Microsoft's strtok_s()
;它们可以安全地用于库函数。您还可以查找 strsep()
.
您可能会发现以下问题之一很有用:
- Need to know when no data appears between two token separators
还有很多其他人可以提供帮助。