gpt4 book ai didi

c - 打破字符串指针直到c中的标记

转载 作者:行者123 更新时间:2023-11-30 14:41:50 25 4
gpt4 key购买 nike

我有一个指针 char * c =“我 - 需要 - 做 - 这个 - 中断”。我需要根据“-”来打破它,以便在每次迭代中我得到的输出为“I”,然后是“I - need”,然后是“I - need - to”,依此类推,直到整个字符串。有什么帮助吗?

最佳答案

简单的方法是使 c 可变,而不是指向字符串文字的指针。这样,您所需要做的就是沿着字符串进行操作(使用指针或索引)并跟踪您是否在单词中。当您点击空格(或连字符,如果去掉空格),如果您在一个单词中,则保存当前字符,用 '\0' 覆盖数组中的当前字符以终止当前字符处的字符串并打印它。恢复数组中的当前字符并重复直到用完字符,例如

#include <stdio.h>

int main (void) {

char c[] = "I - need - to - do - this - break", /* an array */
*p = c; /* pointer to current char */
int in = 0; /* flag for in/out of word */

while (*p) { /* loop over each char */
if (*p == ' ' || *p == '-') { /* if a space or hyphen */
if (in) { /* if in a word */
char current = *p; /* save current char */
*p = 0; /* nul-terminate array at current */
puts (c); /* print array */
*p = current; /* restore current in array */
in = 0; /* set flag out of word */
}
}
else { /* otherwise, not a space or hyphen */
in = 1; /* set flag in word */
}
p++; /* advance to next char */
}

if (in) /* if in word when last char reached */
puts (c); /* output full string */
}

示例使用/输出

$ ./bin/incremental
I
I - need
I - need - to
I - need - to - do
I - need - to - do - this
I - need - to - do - this - break

使用非可变字符串文字

如果您必须使用不可变的字符串文字,那么方法基本上是相同的。唯一的区别是您不能终止原始字符串,因此您只能使用另一个指针(或索引)从头开始输出每个字符,直到使用 putchar 到达当前字符(或获取数字)来自 p - c 的字符,然后复制到缓冲区以立即终止并输出)。只需循环直到到达当前位置并使用 putchar 进行输出就和其他操作一样简单,例如

#include <stdio.h>

int main (void) {

char *c = "I - need - to - do - this - break", /* string literal */
*p = c; /* pointer to current char */
int in = 0; /* flag for in/out of word */

while (*p) { /* loop over each char */
if (*p == ' ' || *p == '-') { /* if a space or hypen */
if (in) { /* if in a word */
char *wp = c; /* get pointer to start */
while (wp < p) /* loop until you reach current */
putchar (*wp++); /* output each char & increment */
putchar ('\n'); /* tidy up with newline */
in = 0; /* set flag out of word */
}
}
else { /* otherwise, not a space or hyphen */
in = 1; /* set flag in word */
}
p++; /* advance to next char */
}

if (in) /* if in word when last char reached */
puts (c); /* output full string */
}

(输出相同)

仔细检查一下,如果有疑问请告诉我。

关于c - 打破字符串指针直到c中的标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54730800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com