gpt4 book ai didi

C - 如何逐行读取字符串?

转载 作者:太空狗 更新时间:2023-10-29 17:21:27 24 4
gpt4 key购买 nike

在我的 C 程序中,我有一个字符串,我想一次处理一行,理想情况下是将每一行保存到另一个字符串中,对所述字符串执行我想要的操作,然后重复。不过,我不知道这将如何实现。

我正在考虑使用 sscanf。 sscanf 中是否存在“读取指针”,就像我从文件中读取时一样?这样做的另一种选择是什么?

最佳答案

如果允许您写入长字符串,下面是一个如何高效执行此操作的示例:

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

int main(int argc, char ** argv)
{
char longString[] = "This is a long string.\nIt has multiple lines of text in it.\nWe want to examine each of these lines separately.\nSo we will do that.";
char * curLine = longString;
while(curLine)
{
char * nextLine = strchr(curLine, '\n');
if (nextLine) *nextLine = '\0'; // temporarily terminate the current line
printf("curLine=[%s]\n", curLine);
if (nextLine) *nextLine = '\n'; // then restore newline-char, just to be tidy
curLine = nextLine ? (nextLine+1) : NULL;
}
return 0;
}

如果您不允许写入长字符串,那么您需要为每一行创建一个临时字符串,以使每行字符串 NUL 终止。像这样:

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

int main(int argc, char ** argv)
{
const char longString[] = "This is a long string.\nIt has multiple lines of text in it.\nWe want to examine each of these lines separately.\nSo we will do that.";
const char * curLine = longString;
while(curLine)
{
const char * nextLine = strchr(curLine, '\n');
int curLineLen = nextLine ? (nextLine-curLine) : strlen(curLine);
char * tempStr = (char *) malloc(curLineLen+1);
if (tempStr)
{
memcpy(tempStr, curLine, curLineLen);
tempStr[curLineLen] = '\0'; // NUL-terminate!
printf("tempStr=[%s]\n", tempStr);
free(tempStr);
}
else printf("malloc() failed!?\n");

curLine = nextLine ? (nextLine+1) : NULL;
}
return 0;
}

关于C - 如何逐行读取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17983005/

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