我有一个项目,需要根据每行文本中的第二个、第三个等单词来对多行文本进行排序,而不是第一个单词。例如:
this line is first
but this line is second
finally there is this line
如果您选择按第二个单词排序,则会变成:
this line is first
finally there is this line
but this line is second
我有一个指向包含每行的字符数组的指针。到目前为止,我所做的是使用strtok()函数将每行分割到第二个单词,但这会将整个字符串更改为仅该单词,并将其存储在我的数组中。我的分词代码如下:
```c char *token = strtok(line, " "); strcpy(myArray[i], token); ```Is there a way to split the line and keep the original string intact? I need to be able to access the entire line later in my code.
for (i = 0; i < numLines; i++) {
char* token = strtok(labels[i], " ");
token = strtok(NULL, " ");
labels[i] = token;
}
这将给我每行的第二个单词,因为我调用了两次strtok。然后我对这些单词进行排序。(line, this, there) 然而,我需要将字符串以其原始形式放回。我知道strtok会将标记转换为'\0',但我还没有找到一种方法来获取原始字符串。
我相信答案在于使用指针,但我不确定下一步需要做什么。
我应该提到,我正在从输入文件中读取行,如下所示:
for (i = 0; i < numLines && fgets(buffer, sizeof(buffer), fp) != 0; i++) {
labels[i] = strdup(buffer);
编辑:我的find_offset方法
size_t find_offset(const char *s, int n) {
size_t len;
while (n > 0) {
len = strspn(s, " ");
s += len;
}
return len;
}
编辑2:用于排序的相关代码
//Getting the line and offset
for (i = 0; i < numLines && fgets(buffer, sizeof(buffer), fp) != 0; i++) {
labels[i].line = strdup(buffer);
labels[i].offset = find_offset(labels[i].line, nth);
}
int n = sizeof(labels) / sizeof(labels[0]);
qsort(labels, n, sizeof(*labels), myCompare);
for (i = 0; i < numLines; i++)
printf("%d: %s", i, labels[i].line); //Print the sorted lines
int myCompare(const void* a, const void* b) { //Compare function
xline *xlineA = (xline *)a;
xline *xlineB = (xline *)b;
return strcmp(xlineA->line + xlineA->offset, xlineB->line + xlineB->offset);
}
labels[i]
将不指向漂亮的子字符串。你确定要这么做吗? - chux - Reinstate Monica