繁体   English   中英

字符串和指针

[英]Strings & Pointers

我有一个与字符串和指针有关的问题。 请仅使用C / C ++程序进行解释。

有一个文件,每行包含一个单词。 我知道没有。 文件中的单词数。 请在小代码的帮助下说明如何将这些字有效地存储在RAM中。

fscanf(fp,"%s",word) & strcpy ,是将单词存储在RAM中的唯一方法。没有其他有效的算法或逻辑可用。

谢谢。

可能最有效的方法是将整个文件读入一个块中的内存(使用fread )。 然后分配一个指针数组,每个单词一个。 然后遍历内存中的文件,将\\n字符更改为\\0 ,并将指针存储在数组中每个\\0之后的指针。

它之所以有效是因为它仅执行一次I / O操作,两次内存分配,并在文件中的字符上循环两次(一次将它们复制到缓冲区,再一次将它们分解为单独的字符串)。 您描述的算法( fscanfstrcpy )将执行许多I / O操作,为每个单词分配内存,并至少循环遍历字符3次(一次读入缓冲区,一次查找要为其分配内存的长度,并一次从缓冲区复制到分配的内存中)。

这是一个没有错误检查的简单版本:

char* buffer; // pointer to memory that will store the file
char** words; // pointer to memory that will store the word pointers

// pass in FILE, length of file, and number of words
void readfile(FILE *file, int len, int wordcnt)
{
    // allocate memory for the whole file
    buffer = (char*) malloc(sizeof(char) * len);
    // read in the file as a single block
    fread(buffer, 1, size, file);

    // allocate memory for the word list
    words = (char**) malloc(sizeof(char*) * wordcnt);
    int found = 1, // flag indicating if we found a word
                   // (starts at 1 because the file begins with a word)
        curword = 0; // index of current word in the word list

    // create a pointer to the beginning of the buffer
    // and advance it until we hit the end of the buffer
    for (char* ptr = buffer; ptr < buffer + len; ptr++)
    {
        // if ptr points to the beginning of a word, add it to our list
        if (found)
            words[curword++] = ptr;
        // see if the current char in the buffer is a newline
        found = *ptr == '\n';
        // if we just found a newline, convert it to a NUL
        if (found)
            *ptr = '\0';
    }
}

这是一个使用strtok简单版本:

char* buffer;
char** words;

void readfile(FILE *file, int len, int wordcnt)
{
    buffer = (char*) malloc(sizeof(char) * len);
    fread(buffer, 1, size, file);
    buffer[len] = '\0';

    words = (char**) malloc(sizeof(char*) * wordcnt);
    int curword = 0;
    char* ptr = strtok(buffer, "\n");
    while (ptr != NULL)
    {
        words[curword++] = ptr;
        ptr = strtok(NULL, "\n");
    }
}

请注意,以上两个示例假定文件中的最后一个单词以换行符结尾!

您可以将整个文件读入一个内存块,然后遍历该块,将每个'\\ r'或'\\ n'替换为0。现在,您只需在该块中搜索紧随其后的字符即可恢复所有字符串一个或多个0。 这与您将获得的空间效率差不多。 现在,如果您还想快速访问,则可以分配另一个指针块,并将每个指针块设置为指向字符串的开头。 比每个指向单独分配的String的指针块还要高效。

如果您希望您的字符串不消耗额外的未使用字节,请执行以下操作:

char * * array=new char*[COUNT_OF_WORDS];


fscanf(fp,"%s",word);
int len=strlen(word);
array[i]=new char[len+1];
strcpy(array[i],word);

为什么要strcpy 只需将fscanf直接插入目标内存即可。

既然如此,您引用了“仅使用C / C ++程序进行解释...。”使用包含字符串的向量很容易std::vector< std::string >

std::string word;

std::vector < std::string > readWords ;  // A vector to hold the read words.

ifstream myfile ("fileToRead.txt");
if (myfile.is_open())
{
    while ( myfile.good() )
    {
       getline (myfile,word);  // This gets you the first word get copied to line.
       readWords.push_back(word) ; // Each read word is being copied to the vector
    }
    myfile.close();
}

所有已读单词都将复制到向量readWords ,您可以对其进行迭代以查看它们的实际含义。

这是一种快速而肮脏的方法,无需进行错误检查,使用静态内存和使用fgets。

#define MAX_NUM_WORDS   10
#define MAX_LEN 128

void get_words(char *p_file, char *words)
{
  FILE *f;

  f = fopen(p_file, "r");
  while (fgets(words, MAX_LEN, f))
    words += MAX_LEN+1;

  fclose(f); 
}

main()
{
  char word_array[MAX_NUM_WORDS][MAX_LEN+1];
  int i;

  get_words("words.txt", word_array);

  for (i=0; i<MAX_NUM_WORDS; i++)
    printf("Word: %s", word_array[i]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM