成语| 古诗大全| 扒知识| 扒知识繁体

当前位置:首页 > 知识百科

编写一个函数删除字符串中的空格

Q1:去除字符串中的空格用什么函数

JAVA中去掉空格
1. String.trim()
trim()是去掉首尾空格
2.str.replace(" ", ""); 去掉所有空格,包括首尾、中间
复制代码 代码如下:String str = " hell o ";
String str2 = str.replaceAll(" ", "");
System.out.println(str2);
3.或者replaceAll(" +",""); 去掉所有空格
4.str = .replaceAll("\s*", "");
可以替换大部分空白字符, 不限于空格
\s 可以匹配空格、制表符、换页符等空白字符的其中任意一个 您可能感兴趣的文章:java去除字符串中的空格、回车、换行符、制表符的小例子

Q2:用C编写一个自定义函数,将字符串s中所有的空格字符删去。(用指针方法)

#include "stdio.h"void main()
{
char t[100];
char *p=t,*s=t;
printf("输入字符串:");
gets(t);
while(*p)
{
if(*p!=32) *s++=*p;
p++;
}
*s=\0;
puts(t);}

Q3:编写一个函数,去掉一个字符串前后的空格字符,并在主函数中调用该函数。(c语言)

#include
char * trim(char *s)
{
char *p,*r;
char *h=s;
p=r=s;
while(*r)r++;//找尾
r--;
while(*r== )r--;//找最后一个字while(*p== )p++;//找第一个字
while(p<=r)
*s++=*p++;
*s=0;
return h;
}
void main()
{
char t[100];
printf("输入字符串:");
gets(t);
printf("结果:%s\n",trim(t));
}WwW.b‖AZHishI.COM

Q4:编写一函数,删除字符串尾部的空格。

char * trim(char *str,char retstr[])
{
char *head,*rear;
int len,count; len = strlen(str);
if (len == 0)
return NULL; head = str;
rear = str + len - 1; while(*head == )
{
head++ ;
}
while(*rear == )
{
rear--;
}
count = rear - head + 1 ;
strncpy(retstr,head,count); return retstr; }
以上是百度 Trim函数 源码 找到的

Q5:请用C语言编写一个函数,用来删除字符串中的所有空格,加上注释哟

很简单的程序,遍历输入字符串。
1、如果字符不是空格,就赋值到输出字符串中。
2、如果是空格,就跳过这个字符。
例如:
#include
#include
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!

Q6:请编写一个函数,用来删除字符串中的所有空格,例如,输入asd af aa z67,则输出为asdafaaz67。

供你参考……
#include "stdio.h"//
void delspace(char *p){
char *p1,*p2;
while(*p){
if(*p++!= ) continue;
p2=p1=p;
p1--;
while(*p1++=*p2++);
}
}
void main(){
char a[]="asd af aa z67 v";
printf("%s\n",a);
delspace(a);
printf("%s\n\n",a);
}www.BAZhishI★.COm

Q7:请编写一个函数,用来删除字符串中的所有空格

很简单的程序,遍历输入字符串,如果字符不是空格,就赋值到输出字符串中,如果是空格,就跳过这个字符。#include #include 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!

猜你喜欢

更多