當前位置:首頁 > 知識百科

編寫一個函數刪除字符串中的空格

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!

猜你喜歡

更多
此页面为HK繁体版,其他版本: 中文简体 | TW 繁体