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

时间:2013-07-31 23:56:31

标签: c cstring

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

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

1 个答案:

答案 0 :(得分:7)

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

#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;
}