C语言字符串查找最长单词的优化方法
C语言查找最长单词的代码优化
原始代码如下:
void FindLongWord(char h[], char word[])
{
int i=0,j=0;
int len=0;
while(h[i] !='\0')
{
j = i;
while(h[j] !='\0' && h[j] !=' ')
{
j++;
len = j-i;
}
if(len > strlen(word)){
strncpy(word,h+i,len);
}
j++;
i = j;
}
}
该代码可以使用指针来遍历字符串,同时可以去掉变量len,直接在判断长度时计算。
简化后的代码如下:
void FindLongWord(char h[], char word[])
{
int max_len = 0;
char *p = h;
while (*p != '\0') {
int len = 0;
while (*p != '\0' && *p != ' ') {
len++;
p++;
}
if (len > max_len) {
max_len = len;
strncpy(word, p - len, len);
}
if (*p != '\0') {
p++;
}
}
}
优化思路:
- 使用指针
p遍历字符串,减少了索引的计算。 - 在内层循环中直接计算长度
len,避免了使用额外的变量。 - 使用
strncpy(word, p - len, len)将最长单词复制到word中,简化了代码。
通过以上优化,代码更加简洁高效。
原文地址: https://www.cveoy.top/t/topic/nBd4 著作权归作者所有。请勿转载和采集!