MST
星途 面试题库

面试题:C语言复杂字符串处理及字符数组优化

假设有一个字符数组存储了一段英文文章,其中包含单词、标点符号和空格。编写一个C程序,统计文章中单词的数量,并将文章按单词逆序排列(单词内部顺序不变),同时优化字符数组的使用,尽量减少额外空间的占用。注意处理边界情况,如连续空格、文章开头和结尾的空格等。
35.9万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <string.h>
#include <ctype.h>

// 函数声明
void reverseWords(char *str);
int countWords(char *str);

int main() {
    char article[1000];
    printf("请输入英文文章: ");
    fgets(article, sizeof(article), stdin);
    // 去除fgets读取的换行符
    article[strcspn(article, "\n")] = '\0';

    int wordCount = countWords(article);
    printf("单词数量: %d\n", wordCount);

    reverseWords(article);
    printf("逆序排列后的文章: %s\n", article);

    return 0;
}

// 统计单词数量
int countWords(char *str) {
    int count = 0;
    int inWord = 0;
    for (int i = 0; str[i] != '\0'; i++) {
        if (isalnum(str[i])) {
            if (!inWord) {
                count++;
                inWord = 1;
            }
        } else {
            inWord = 0;
        }
    }
    return count;
}

// 逆序排列单词
void reverseWords(char *str) {
    int len = strlen(str);
    int start = 0, end = 0;

    // 去除开头的空格
    while (isspace(str[start])) start++;

    // 去除结尾的空格
    while (len > 0 && isspace(str[len - 1])) len--;
    str[len] = '\0';

    for (int i = start; i <= len; i++) {
        if (isspace(str[i]) || str[i] == '\0') {
            end = i - 1;
            // 逆序单词
            while (start < end) {
                char temp = str[start];
                str[start] = str[end];
                str[end] = temp;
                start++;
                end--;
            }
            start = i + 1;
            while (isspace(str[start])) start++;
            i = start - 1;
        }
    }

    // 整体逆序字符串
    start = 0;
    end = len - 1;
    while (start < end) {
        char temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        start++;
        end--;
    }
}