在C中删除字符串的前导空格并复制到dest数组

时间:2019-02-13 04:37:08

标签: c

我正在尝试找出如何复制删除前导空格的修剪后的字符串并使用指针/不使用指针将其存储到dest数组中的方法。

这就是我尝试过的。

<filter>
    <filter-name>checkCertainAttribute</filter-name>
    <filter-class>CheckCertainAttributeFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>checkCertainAttribute</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

打印出:

#include <stdio.h>
#include <ctype.h> 
#include <string.h> 
void trim_copy(char dest[], char src[]){
  char *p = src;
  size_t i;
  size_t counter = 0;
  size_t length = strlen(src);
  while(!isspace(src[counter]) && counter < length){
    p++;
    counter++; /*move the pointer to next index of string if it's a space*/
  }
  for (i = 0; i< length-counter; i++) {
    dest[i] = *p; 
    p++;
  }

}

int main(void){
  char string_with_space_dest[20];
  ltrim_copy(string_with_space_dest, "       hello");
  printf("after removing leading space %s\n",string_with_space_dest );
  return 0;
}

它可以编译,但是根本无法工作。

如果src数组是const并且您不能使用指针该怎么办?

after removing leading space        hello

1 个答案:

答案 0 :(得分:1)

isspace函数用于检查参数是否包含任何空格字符,因此您需要删除not运算符,因为要跳过空格,并且在复制到dest数组后最后需要将null字符分配给dest数组。

#include <stdio.h>
#include <ctype.h> 
#include <string.h> 
void ltrim_copy(char dest[], char src[]){
  char *p = src;
  size_t i;
  size_t counter = 0;
  size_t length = strlen(src);
  while(isspace(src[counter]) && counter < length){
    p++;
    counter++; /*move the pointer to next index of string if it's a space*/
  }
  for (i = 0; i< length-counter; i++) {
    dest[i] = *p; 
    p++;
  }
  dest[i] = '\0';
}

int main(void){
  char string_with_space_dest[20];
  ltrim_copy(string_with_space_dest, "       hello");
  printf("after removing leading space %s\n",string_with_space_dest );
  return 0;
}