就要筛选出空格字符。
要筛选,就要对首字符做标记。
要所有空格,就要遍历。
~
②命令行
#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)
// 修改如下:#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()
}
#include <stdio.h>
int main()
{
char *p="I am Chinese"
char c
int i = 0
while((c = p[i++])!='\0'){
if(c!=' ')
putchar(c)
}
}
扩展资料:
字符串的函数应用
1. 连接运算 concat(s1,s2,s3…sn) 相当于s1+s2+s3+…+sn。
例:concat('11','aa')='11aa'
2. 求子串。 Copy(s,I,I) 从字符串s中截取第I个字符开始后的长度为l的子串。
例:copy(‘abdag',2,3)='bda'
3. 删除子串。过程 Delete(s,I,l) 从字符串s中删除第I个字符开始后的长度为l的子串。
例:s:='abcde'delete(s,2,3)结果s:='ae'
4. 插入子串。 过程Insert(s1,s2,I) 把s1插入到s2的第I个位置。
例:s:=abcinsert('12',s,2)结果s:='a12bc'
5. 求字符串长度 length(s) 例:length('12abc')=5。
在ASP中 求字符串长度用 len(s)例: len("abc12")=5
6. 搜索子串的位置 pos(s1,s2) 如果s1是s2的子串 ,则返回s1的第一个字符在s2中的位置,若不是子串,则返回0。
例:pos(‘ab','12abcd')=3
参考资料:
百度百科-字符串