0

我在主函数中编写以下字符串:

char* dict[] = { "ball", "aba", "bla" };

我的问题是:

我能从这个字符串中取出一个完整的单词吗?

例如,如果我想复制整个单词,我可以这样做:( str[j] = dict[i]; 当然是在某个循环中)

#include<string.h>重要的是要注意,由于问题的要求,我无法使用该库

4

1 回答 1

2

C 中的字符串是“空终止”。char它实际上是一个以“0”结尾的数组。例如,我们有:

char* str = "abc";

该语句将创建一个包含 4 个元素的数组,'a', 'b', 'c', 0,str是指向数组的指针(或指向数组第一个元素的指针)。而 的值str只是一个地址,也就是一个整数。如果您以 str[j] = dict[i] 仅复制地址的方式复制字符串(浅复制)。它不会复制字符串。

在您的情况下,您创建一个字符串列表(char 数组),并且dict[i]是指向第 i 个字符串的第一个元素的指针。换句话说,我们可以dict[i]像处理常规字符串一样处理(例如str在我的示例中)。

这是创建列表的深层副本的示例。

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

int main() {
    char* dict[] = { "ball", "aba", "bla" };
    char** copy = (char**) malloc((3) * sizeof(char*));
    for (int i=0; i<3; i++) {
        char *shallowCopy = dict[i];
        int length = 0;
        
        while (shallowCopy[length] != 0) length ++; // find the length of the string
        // printf("length: %d\n", length);
        
        char *deepCopy = (char*) malloc((length + 1) * sizeof(char)); // +1 for null terminated
        deepCopy[length] = 0; // null terminated
        
        while(length >0) deepCopy[--length] = shallowCopy[length];

        copy[i] = deepCopy; // is deepCopy what you mean "to take a whole word out of this string (list)"?
    }
    
    for (int i=0; i<3; i++) {
        printf("%s\n", copy[i]);
    }   
}
于 2020-07-16T21:38:23.120 回答