如何仅使用 <iostream>?

How do I tokenize a string only using <iostream>?

本文关键字:iostream gt lt 何仅使      更新时间:2023-10-16

我想学习如何标记字符串,就像 strtok 函数仅使用<iostream>一样。

我制作了一个删除空格的程序,但我认为它与 strtok 不同。

#include <iostream>
int main(){
int i = 0;
char s[100]="fix the car";
while(s[i] != ''){
if(s[i] == ' ')
s[i] = s[i-1];
else std::cout << s[i];
i++;
}
return 0;
}
prints: fixthecar

我想要整个strtok函数,而不仅仅是删除分隔符,听说我必须使用指针,但我不知道如何编码。

这里已经讨论了strtok的内部实现,在提出新问题之前,您应该检查一下。

strtok()操作的关键是在保密调用之间保留最后一个分隔符的位置(这就是为什么strtok()继续解析在连续调用中使用null pointer调用时传递给它的非常原始的字符串(。

看看这个strtok()实现,它的功能与strtok()提供的功能略有不同

char *zStrtok(char *str, const char *delim) {
static char *static_str=0;      /* var to store last address */
int index=0, strlength=0;           /* integers for indexes */
int found = 0;                  /* check if delim is found */
/* delimiter cannot be NULL
* if no more char left, return NULL as well
*/
if (delim==0 || (str == 0 && static_str == 0))
return 0;
if (str == 0)
str = static_str;
/* get length of string */
while(str[strlength])
strlength++;
/* find the first occurance of delim */
for (index=0;index<strlength;index++)
if (str[index]==delim[0]) {
found=1;
break;
}
/* if delim is not contained in str, return str */
if (!found) {
static_str = 0;
return str;
}
/* check for consecutive delimiters
*if first char is delim, return delim
*/
if (str[0]==delim[0]) {
static_str = (str + 1);
return (char *)delim;
}
/* terminate the string
* this assignmetn requires char[], so str has to
* be char[] rather than *char
*/
str[index] = '';
/* save the rest of the string */
if ((str + index + 1)!=0)
static_str = (str + index + 1);
else
static_str = 0;
return str;
}