大家想要
删除字符数组或者
字符串数组的首尾
字符时首先想到的就是strtrim
函数,但是这个
函数有限制,就是其只能
删除首尾的空白
字符,而当我们想要
删除其他特定
字符时,就无能为力了。
例如如下代码,strtrim
函数很好的
删除了(连续)空白
字符,但是不能
删除特定
字符,比如星号等等。
%
Matlab
stra = ' hello world ';
strb = " hello world ";
strc = " hello world *";
Fa = strtrim(stra);
<br />/*删除字符串中的数字并压缩字符串(神州数码以前笔试题),
如字符串"abc123de4fg56"处理后变为"abcdefg"。注意空间和效率*/
#include <cstdlib>
#include <iostream>
using namespace std;
void hanStr(char *str)
int len = strlen(str);
int index = 0;
for(int i=0; i<len; i++)
1. 定义一个新的字符串,长度为两个字符串长度之和加1(加1是为了留出字符串结尾的'\0')。
2. 使用循环将第一个字符串的每个字符依次复制到新字符串中。
3. 再使用循环将第二个字符串的每个字符依次复制到新字符串中。
4. 在新字符串的最后一个位置加上'\0',表示字符串的结尾。
5. 最后输出新字符串即可。
示例代码如下:
#include <stdio.h>
int main()
char str1[100], str2[100], new_str[200];
int i, j;
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
// 将第一个字符串复制到新字符串中
for (i = 0; str1[i] != '\0'; i++)
new_str[i] = str1[i];
// 将第二个字符串复制到新字符串中
for (j = 0; str2[j] != '\0'; j++)
new_str[i + j] = str2[j];
// 在新字符串的最后一个位置加上'\0'
new_str[i + j] = '\0';
printf("连接后的字符串为:%s\n", new_str);
return 0;