C-如何逐行读取字符串? [英] C - How to read a string line by line?

查看:332
本文介绍了C-如何逐行读取字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C程序中,我有一个字符串,希望一次处理一行,理想情况下,是将每一行保存到另一字符串中,用该字符串做我想做的,然后重复。不过,我不知道如何实现。

In my C program, I have a string that I want to process one line at a time, ideally by saving each line into another string, doing what I want with said string, and then repeating. I have no idea how this would be accomplished, though.

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

I was thinking of using sscanf. Is there a "read pointer" present in sscanf like there would be if I was reading from a file? What would be another alternative for doing this?

推荐答案

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

Here's an example of how you can do it efficiently, if you are allowed to write into the long string:

#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终止,将需要为每行创建一个临时字符串。诸如此类:

If you're not allowed to write into the long string, then you'll need to make a temporary string for each line instead, in order to have the per-line string NUL terminated. Something like this:

#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-如何逐行读取字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆