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

如何在C语言中实现自定义trim()函数?

C语言文本首尾空格去除作业优化问题

需求:完成一项作业,要求移除文本首尾的空格(不确定首尾是否存在空格)。例如输入为" Pls help me"时,输出需为"Pls help me"(无前导空格),只能使用<stdio.h>和<string.h>标准库。

现有代码如下:

#include <stdio.h>
#include <string.h>

int *pIndexf; // pointer Index front (of the text)
int *pIndexe; // pointer Index end (of the text)

void trim(char source[], int size) {
  
  // Checking the array from the front
  for (int i = 0; i < strlen(source); i++) {
    if (source[i] == ' ') {
        pIndexf = &i;
        break;
    }
  } 

  // Checking the array from behind
  for (int i = strlen(source)-1; i > 0; i--) {
    if (source[i] == ' ') {
       pIndexe = &i;
      break;
    }
  }
}

int main() {
  char source[31] = {" Random text "}; // the array where i store the text i have to manipulate
  char goal[31]; // this is where the trimmed text should be

  trim(source, 31);
  
// Here i would add the source array's elements to the goal list without the spaces in a loop
}

诉求:希望把全局指针改成指向main函数内变量的指针,不再使用全局变量,同时需要搞懂指针的用法。


问题分析与修正方案

1. 指针核心用法:摒弃全局变量,用指针参数传递

全局变量的问题在于函数依赖全局状态,复用性差,还容易引发意外错误。正确的做法是在main里定义存储首尾索引的变量,把它们的地址传给trim函数,让函数直接修改main里的变量值。

指针的基础规则:

  • &变量名:获取变量的内存地址
  • *指针变量:解引用指针,访问/修改指针指向的内存里的值

2. 修正原trim函数的逻辑错误

原代码的查找逻辑完全颠倒了:

  • 从前往后找时,应该跳过所有开头空格,找到第一个非空格字符的索引,而非找到第一个空格就停止
  • 从后往前找时,应该跳过所有结尾空格,找到最后一个非空格字符的索引,而非找到第一个空格就停止
  • 还要处理全是空格的极端情况

3. 完整修正后的代码

#include <stdio.h>
#include <string.h>

// 接收source字符串,以及两个指针,用来存储首尾非空格的索引
void trim(char source[], int *start, int *end) {
    int len = strlen(source);
    // 找开头第一个非空格的索引
    *start = 0;
    while (*start < len && source[*start] == ' ') {
        (*start)++;
    }
    // 找结尾最后一个非空格的索引
    *end = len - 1;
    while (*end >= 0 && source[*end] == ' ') {
        (*end)--;
    }
    // 处理全是空格的情况:此时start > end
    if (*start > *end) {
        *start = 0;
        *end = -1;
    }
}

int main() {
    char source[31] = {" Random text "};
    char goal[31];
    int start_idx, end_idx; // 存储首尾索引的变量

    // 把两个变量的地址传给trim函数
    trim(source, &start_idx, &end_idx);

    // 复制有效字符到goal数组
    int goal_idx = 0;
    for (int i = start_idx; i <= end_idx; i++) {
        goal[goal_idx++] = source[i];
    }
    // 字符串必须加结束符
    goal[goal_idx] = '\0';

    printf("原字符串: \"%s\"\n", source);
    printf("修剪后: \"%s\"\n", goal);
    return 0;
}

代码解释

  • 在main里定义start_idx和end_idx两个int变量,用来存修剪后的首尾位置
  • 调用trim时用&start_idx和&end_idx把变量地址传进去,这样trim里的*start和*end直接操作的就是main里的这两个变量
  • trim函数的循环逻辑:从开头跳过所有空格,从结尾跳过所有空格,最后处理全空格的情况
  • 复制字符到goal时,从start_idx到end_idx遍历,最后一定要加'\0',否则不是合法的C字符串

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 15:30:08