You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言字符串操作练习,求四个自定义函数的实现代码

C语言字符串操作练习题函数实现

以下四个函数均兼容常规题目要求的参数、返回值定义,依赖<ctype.h>头文件的字符判断/转换方法,可直接替换题目标注的/* Your Code Here */块使用。


1. 统计字符串字符总数 count_characters

功能:统计字符串中除结束符\0外的所有字符总数,包含空格、标点等特殊字符。

int count_characters(char *str) {
    int cnt = 0;
    while (str[cnt] != '\0') cnt++;
    return cnt;
}

2. 统计字符串单词总数 count_words

功能:按「空白符分隔的连续非空白序列为1个单词」的规则统计单词数,自动过滤首尾、连续空白的计数干扰。

#include <ctype.h>
int count_words(char *str) {
    int cnt = 0, in_word = 0;
    while (*str != '\0') {
        if (isspace(*str)) {
            in_word = 0;
        } else if (!in_word) {
            in_word = 1;
            cnt++;
        }
        str++;
    }
    return cnt;
}

3. 单词首字母大写 capitalize

功能:将每个单词的首字母转为大写,其余字符保持原样,若需要其余字母统一转小写可放开注释的代码行。

#include <ctype.h>
void capitalize(char *str) {
    int new_word = 1;
    while (*str != '\0') {
        if (isspace(*str)) {
            new_word = 1;
        } else if (new_word) {
            *str = toupper(*str);
            new_word = 0;
        } 
        // 若要求非首字母统一转小写,放开下一行注释即可
        // else *str = tolower(*str);
        str++;
    }
}

4. 反转字母大小写 invert_capitalization

功能:大写字母转小写,小写字母转大写,非字母字符不做修改。

#include <ctype.h>
void invert_capitalization(char *str) {
    while (*str != '\0') {
        if (isupper(*str)) {
            *str = tolower(*str);
        } else if (islower(*str)) {
            *str = toupper(*str);
        }
        str++;
    }
}

内容的提问来源于stack exchange,提问作者gg1973

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 01:06:08