[英]Find Lexicographically Greatest Word in a String - C Pointers
EDIT: Edited everything sorry for misunderstandings.编辑:编辑了一切对不起误解。
I'm trying to write a function to find the lexicographically greatest word in a string.我正在尝试编写 function 来查找字符串中字典顺序上最大的单词。
A word is defined as so: contains a letter - can use isalpha() - and does not contain spaces - can use isspace()一个词是这样定义的:包含一个字母 - 可以使用 isalpha() - 不包含空格 - 可以使用 isspace()
If s = "He llo wor ld "如果 s = "He llo 世界"
s contains the following words: He, llo, wor, l, d. s 包含以下词:He、llo、wor、l、d。
To find the lexicographically greatest word between two strings, I can use strcmp.要查找两个字符串之间的字典顺序最大的单词,我可以使用 strcmp。
The function prototype is: char *biggestWord(char *s) and it should return the lexicographically greatest word. function 原型是: char *biggestWord(char *s) 它应该返回字典序上最大的单词。
I'm literally stuck with it for hours.我真的坚持了几个小时。 Here's what I tried to do:
这是我试图做的:
I'm stuck on what to do next.我被困在下一步该怎么做。 My algorithm idea wouldn't even work if there is two spaces in a row.
如果连续有两个空格,我的算法想法甚至都行不通。
char *biggestWord(char *s) {
//We will find the first string and compare it to each one of the new strings
//We will keep the value of the higher string everytime
char *res;
char *temp;
int indexStart = 0; //Will contain the index of the first character to then store on temp
int indexEnd = 0; //Will contain the index of the last character to then store on temp
for(int i = 0; s[i] != '\0'; i++) {
if(isspace(s[i])) {
indexEnd = i - 1;
temp = myStrCpy(s, indexStart, indexEnd); //Will extract the string using start and end index, and put it into temp
indexStart = i+1;
}
}
} }
Here is a possible solution:这是一个可能的解决方案:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char* biggestWord(char* s)
{
// Create a buffer for bigest word
char* buf = calloc(strlen(s) + 1, sizeof(char));
if (buf == NULL)
return NULL;
// Create a buffer for current word
char* word = malloc(strlen(s) + 1 * sizeof(char));
if (word == NULL)
return NULL;
int j = 0;
for (int i = 0; s[i]; i++) {
if (isspace(s[i])) {
// We found end of word, replace the space by a nul byte
strncpy(word, s + j, i - j);
word[i - j] = 0; // nul terminate
if (strcmp(buf, word) < 0) {
// we got a bigger word according to strcmp()
strcpy(buf, word);
// skip remaining spaces
while (s[i] && isspace(s[i]))
i++;
// Remember where a word starts
j = i;
}
}
}
free(word);
return buf; // cAller must call free()
}
void main(void)
{
char* res = biggestWord("He llo wor l d ");
if (res) {
printf("Result=\"%s\"", res);
free(res);
}
}
biggestWord
return a pointer to dynamically allocated string, so it must be freed by caller. biggestWord
返回一个指向动态分配的字符串的指针,因此它必须由调用者释放。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.