c語言實現去除字符串首尾空格


字符串內存圖如下:

引入頭文件:

 1 #include<stdlib.h>
 2 #include<stdio.h>
 3 #include<string.h>

 函數原型:

1 void trim(char *strIn /*in*/, char *strOut /*in*/);

實現方法一:

void trim(char *strIn, char *strOut){

    int i, j ; i = 0; j = strlen(strIn) - 1; while(strIn[i] == ' ') ++i; while(strIn[j] == ' ') --j; strncpy(strOut, strIn + i , j - i + 1); strOut[j - i + 1] = '\0'; }

實現方法二:

 1 void trim(char *strIn, char *strOut){
 2 
 3     char *start, *end, *temp;//定義去除空格后字符串的頭尾指針和遍歷指針
 4     
 5     temp = strIn; 6 7 while (*temp == ' '){ 8 ++temp; 9  } 10 11 start = temp; //求得頭指針 12 13 temp = strIn + strlen(strIn) - 1; //得到原字符串最后一個字符的指針(不是'\0') 14 15 printf("%c\n", *temp); 16 17 while (*temp == ' '){ 18 --temp; 19  } 20 21 end = temp; //求得尾指針 22 23 24 for(strIn = start; strIn <= end; ){ 25 *strOut++ = *strIn++; 26  } 27 28 *strOut = '\0'; 29 }

測試:

 1 void main(){
 2     char *strIn = "   ak kl  p  "; 3 4 char strOut[100]; 5 6  trim(strIn, strOut); 7 8 printf("*%s*\n",strOut); 9 10 system("pause"); 11 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM