從0下標開始,一個字符一個字符地自己向自己拷貝,當拷入一個空格時,將后面的空格跳過去。設置2個初值為0的變量i和j,i用來控制遍歷原字符串數組,j用來記錄新拷入的字符位置,用下面的代碼就可實現!
堅守“ 做人真誠 · 做事靠譜 · 口碑至上 · 高效敬業 ”的價值觀,專業網站建設服務10余年為成都假山制作小微創業公司專業提供成都定制網站營銷網站建設商城網站建設手機網站建設小程序網站建設網站改版,從內容策劃、視覺設計、底層架構、網頁布局、功能開發迭代于一體的高端網站建設服務。
//#include?"stdafx.h"http://If?the?vc++6.0,?with?this?line.
#include?"stdio.h"
int?main(void){
char?str[1000];
int?i,j;
gets(str);
for(j=i=0;str[i];i++){
if((str[j++]=str[i])=='?'){//自己向自己拷貝,直到遇見'?'
for(i++;str[i]=='?';i++);//遇到'?'跳過后面的'?'
i--;
}
}
str[j]='\0';//補個結束符
printf("%s\n",str);//打出來看看
return?0;
}
//?修改如下:
#include?stdio.h
#include?stdlib.h
#include?string.h
void?trimSpace(char?*instr,?char?*outstr){
int?i?=?0;
int?j?=?0;?//?因為去掉空格后的字符串的字符個數和去掉空格之前不一樣,需要額外增加一個變量用來標記下標。
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();
}
很簡單的程序,遍歷輸入字符串。
1、如果字符不是空格,就賦值到輸出字符串中。
2、如果是空格,就跳過這個字符。
例如:
#include
stdio.h
#include
string.h
int
main()
{
const
char
*
input
=
"Hello
World!
Welcome
To
Beijing!";
char
output[1024];
int
i,
j,
input_len;
input_len
=
strlen(input);
j
=
0;
for(i
=
0;
i
input_len;
i++)
{
if
(input[i]
!=
'
')
{
output[j]
=
input[i];
j++;
}
}
output[j]
=
'\0';
printf("Input
string
is:
%s\n",
input);
printf("After
spaces
were
removed:
%s\n",
output);
return
0;
}
具體的輸出效果為:
Input
string
is:
Hello
World!
Welcome
To
Beijing!
After
spaces
were
removed:
HelloWorld!WelcomeToBeijing!
/*去除字符串右邊空格*/
void
vs_strrtrim(char
*pstr)
{
char
*ptmp
=
pstr+strlen(pstr)-1;
while
(*ptmp
==
'
')
{
*ptmp
=
'\0';
ptmp--;
}
}
/*去除字符串左邊空格*/
void
vs_strltrim(char
*pstr)
{
char
*ptmp
=
pstr;
while
(*ptmp
==
'
')
{
ptmp++;
}
while(*ptmp
!=
'\0')
{
*pstr
=
*ptmp;
pstr++;
ptmp++;
}
*pstr
=
'\0';
}
①目標
要刪除字符串中的所有空格,
就要篩選出空格字符。
要篩選,就要對首字符做標記。
要所有空格,就要遍歷。
~
②命令行
#include stdio.h
#include stdlib.h
#include ctype.h
~
③定義函數
void fun(char *str)
{int i=0;
char *p;
/*標記:p=str表示指針指向字符串首地址做標記*/
for(p=str;*p!='\0';p++)
/*遍歷:不等于'\0'表示只要字符串不結束,就一直p++。*/
if(*p!=' ')str[i++]=*p;
/*刪除:如果字符串不等于空格,即有內容就存入字符串。等于空格就不儲存,但是指針還是p++繼續后移,跳過儲存空格相當于刪除。*/
}
void fun(char *str)
{int i=0;
char *p=str;
while(*p)
{if(*p!=' ')str[i++]=*p;
p++;}
/*除了for循環遍歷,也可while循環遍歷。注意 p++在if語句后,不然會漏掉第一個字符。*/
str[i]='\0';
/*循環完畢要主動添加'\0'結束字符串。*/
~
④主函數
viod main()
{char str[100];
int n;
printf("input a string:");
get(str);
puts(str);
/*輸入輸出原字符串*/
fun(str);
/*利用fun函數刪除空格*/
printf("str:%s\n",str);
當前文章:去除空格的函數c語言,c++去空格函數
文章URL:http://vcdvsql.cn/article42/heghec.html
成都網站建設公司_創新互聯,為您提供品牌網站制作、App開發、品牌網站建設、外貿網站建設、做網站、商城網站
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯