c语言 将字符串中空格删去
时间: 2023-06-21 15:21:45 浏览: 46
在C语言中,您可以使用`string.h`库中的函数`strcpy()`和`isspace()`来删除字符串中的空格。以下是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void removeSpaces(char *str)
{
int i, j;
for (i = 0, j = 0; str[i]; i++)
if (!isspace(str[i]))
str[j++] = str[i];
str[j] = '\0';
}
int main()
{
char str[] = "This is a string with spaces";
printf("Original String: %s\n", str);
removeSpaces(str);
printf("String with spaces removed: %s\n", str);
return 0;
}
```
这将输出:
```
Original String: This is a string with spaces
String with spaces removed: Thisisastringwithspaces
```
请注意,`isspace()`函数用于检查给定字符是否为空格字符。如果字符为空格,则该函数返回非零值,否则返回零。
相关问题
什么方法可以删除字符串中空格
有多种方法可以删除字符串中的空格,以下是其中的几种方法:
1. 使用 replace() 方法:可以使用 Python 字符串的 replace() 方法将空格替换为空字符串。例如:
```
my_string = "This is a string with spaces."
new_string = my_string.replace(" ", "")
print(new_string)
```
输出结果为:`Thisisastringwithspaces.`
2. 使用 split() 和 join() 方法:可以使用 Python 字符串的 split() 方法将字符串拆分成单词列表,然后使用 join() 方法将列表中的单词连接起来。在连接时,可以指定一个空字符串作为单词之间的分隔符。例如:
```
my_string = "This is a string with spaces."
word_list = my_string.split()
new_string = "".join(word_list)
print(new_string)
```
输出结果为:`Thisisastringwithspaces.`
3. 使用正则表达式:可以使用 Python 的 re 模块中的 sub() 方法使用正则表达式替换空格。例如:
```
import re
my_string = "This is a string with spaces."
new_string = re.sub(r"\s+", "", my_string)
print(new_string)
```
输出结果为:`Thisisastringwithspaces.`
matlab中将字符串中间的空格删除
在MATLAB中,我们可以使用函数strrep来删除字符串中间的空格。该函数的语法如下:
newStr = strrep(str, ' ', '')
其中,str是要处理的字符串,' '表示空格,''表示要替换为空格的字符。
举个例子,假设我们有一个字符串str = 'hello world',其中有三个连续的空格。我们可以使用strrep来删除这些空格,得到新的字符串newStr,代码如下:
str = 'hello world';
newStr = strrep(str, ' ', '')
运行上述代码,我们会得到新的字符串newStr = 'helloworld',中间的空格已经被成功删除了。
需要注意的是,strrep函数只会将字符串中第一次出现的空格替换为空字符。如果要删除字符串中所有的空格,我们可以使用正则表达式函数regexprep。代码如下:
str = 'hello world';
newStr = regexprep(str, '\s', '')
其中,'\s'表示空白字符,包括空格、制表符、换行符等。通过这种方式,我们可以删除字符串中间的所有空格,得到新的字符串newStr。