char *lengthOfLastWord(const char* s) { char* p = (char*)calloc(strlen(s) + 1, sizeof(char)); assert(s != NULL); if (s == NULL) return NULL; int count = 0;//计数器 int max = 0;//记录最大的单词位数 int cur = 0;//字符串拷贝的下标 int i = 0; for (; i < (int)strlen(s); i++) { if (isalpha(s[i])) { count++;//如果是单词就计数器加加 } else { if (max < count) { max = count;//替换最大单词 cur = i; } count = 0; } } if (max < count)//处理尾部 { max = count; cur = i; } strncpy(p, s + (cur - max), max); return p; } int main() { const char arr[] = "abas dsaddsa"; char* p = lengthOfLastWord(arr); printf("%sn", p); free(p); return 0; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)