如何使这个(自己的)trim() 函数在 C 中工作?

问题描述 投票:0回答:1

我必须做一个分配,我必须删除文本末尾和前面的空格。 (不知道前面还是后面总有一个。)

例如,如果我的输入是“请帮助我”,那么我的输出必须是“请帮助我”(前面没有空格。) 我无法再使用我现在正在使用的任何库。

#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
}

如果我可以使用指针指向主函数而不是将它们用作全局变量,那就更好了。

我希望我的问题是可以理解的。

ps.:我不太懂指针。

arrays c function pointers trim
1个回答
0
投票

你的任务不同。您需要目标数组的大小以免其溢出。

char *trim(const char *source, char *dest, size_t size)
{
    const char *end = source;
    char *head = dest;
    if(source && dest && size)
    {   
        if(*source)
        {
            while(*(end + 1)) end++;
            while(end > source)
            {
                if(*end != ' ') break;
                else end--;
            }
            while(*source == ' ') source++;
            while(source <= end && --size) *dest++ = *source++;
        }
        *dest = 0;
    }
    return head;
}
© www.soinside.com 2019 - 2024. All rights reserved.