簡體   English   中英

在C中刪除字符串的前導空格並復制到dest數組

[英]Removing leading space of string in C and copy to the dest array

我試圖弄清楚如何復制刪除前導空格的修剪后的字符串,並使用指針/不使用指針將其存儲到dest數組中。

這就是我嘗試過的。

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

打印輸出:

after removing leading space        hello

它可以編譯,但根本無法工作。

如果src數組是const並且您不能使用指針怎么辦?

void trim_copy(char dest[], const char src[]){}

isspace函數用於檢查參數是否包含任何空格字符,因此您需要刪除not運算符,因為您要跳過空格,並且在復制到dest數組后最后需要將空字符分配給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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM