新聞中心
c語言去掉字符串的空格函數(shù)trim
c語言去掉字符串的空格函數(shù) void trim(char *s){} 如下:
網(wǎng)站的建設(shè)創(chuàng)新互聯(lián)建站專注網(wǎng)站定制,經(jīng)驗豐富,不做模板,主營網(wǎng)站定制開發(fā).小程序定制開發(fā),H5頁面制作!給你煥然一新的設(shè)計體驗!已為成都辦公窗簾等企業(yè)提供專業(yè)服務(wù)。
#include stdio.h
void trim(char *s){
int i,L;
L=strlen(s);
for (i=L-1;i=0;i--) if (s[i]==' ')strcpy(s+i,s+i+1);
}
int main(){
char s[100];
printf("input 1 line string\n");
gets(s);
trim(s);
printf("%s\n",s);
return 0;
}
例如:
input 1 line string
abc 123 XYZ |
輸出:abc123XYZ|
C語言-刪除字符串空格
①目標(biāo)
要刪除字符串中的所有空格,
就要篩選出空格字符。
要篩選,就要對首字符做標(biāo)記。
要所有空格,就要遍歷。
~
②命令行
#include stdio.h
#include stdlib.h
#include ctype.h
~
③定義函數(shù)
void fun(char *str)
{int i=0;
char *p;
/*標(biāo)記:p=str表示指針指向字符串首地址做標(biāo)記*/
for(p=str;*p!='\0';p++)
/*遍歷:不等于'\0'表示只要字符串不結(jié)束,就一直p++。*/
if(*p!=' ')str[i++]=*p;
/*刪除:如果字符串不等于空格,即有內(nèi)容就存入字符串。等于空格就不儲存,但是指針還是p++繼續(xù)后移,跳過儲存空格相當(dāng)于刪除。*/
}
void fun(char *str)
{int i=0;
char *p=str;
while(*p)
{if(*p!=' ')str[i++]=*p;
p++;}
/*除了for循環(huán)遍歷,也可while循環(huán)遍歷。注意 p++在if語句后,不然會漏掉第一個字符。*/
str[i]='\0';
/*循環(huán)完畢要主動添加'\0'結(jié)束字符串。*/
~
④主函數(shù)
viod main()
{char str[100];
int n;
printf("input a string:");
get(str);
puts(str);
/*輸入輸出原字符串*/
fun(str);
/*利用fun函數(shù)刪除空格*/
printf("str:%s\n",str);
c語言 字符串去掉空格
//?修改如下:
#include?stdio.h
#include?stdlib.h
#include?string.h
void?trimSpace(char?*instr,?char?*outstr){
int?i?=?0;
int?j?=?0;?//?因為去掉空格后的字符串的字符個數(shù)和去掉空格之前不一樣,需要額外增加一個變量用來標(biāo)記下標(biāo)。
for?(i?=?0;?i??(int)strlen(instr);?i++)
{
if?((int)(*(instr+i))==32)
{
continue;
}
else{
*(outstr?+?j)?=?*(instr?+?i);
j++;
}
printf("%c",?*(outstr+i));?//這個位置可以打印出來去掉空格之后的字符串
}
*(outstr?+?j)?=?'\0';
printf("%s",?*outstr);?//這個位置再打印就是null了?求解為什么?感謝
}
void?main(){
char?*p1?=?"???abcdefgdddd????";
char?p2[100]?=?{0};
trimSpace(p1,p2);
//printf("%s",?p2);
getchar();
}
網(wǎng)頁題目:c語言去掉字符串空格函數(shù) c語言去除字符串中的空格
標(biāo)題URL:http://www.ef60e0e.cn/article/dodjgde.html