请编写函数,规定输入的字符串只包含字母和*号,其功能是将字符串的前导*全部删除,中间和尾部的*不删除。 例如,字符串中内容是:*******A*BC*DEF*G****。用C语言写
时间: 2024-03-18 16:37:22 浏览: 30
你可以使用以下C语言代码来实现该功能:
```c#include <stdio.h>
#include <string.h>
void removeLeadingStars(char* str) {
int len = strlen(str);
int i = 0;
// 找到第一个非*字符的位置
while (str[i] == '*') {
i++;
}
// 将非*字符前的*删除
if (i > 0) {
memmove(str, str + i, len - i + 1);
}
}
int main() {
char str[] = "*******A*BC*DEF*G****";
removeLeadingStars(str);
printf("处理后的字符串为:%s\n", str);
return 0;
}
```
运行以上代码,输出结果为:处理后的字符串为:A*BC*DEF*G****
相关问题
规定输入的字符串中只包含字母和*号。请编写函数fun,其功能是:只删除字符 前导和
题目中要求编写函数fun,功能是只删除字符串中的前导和后导的字符。
假设输入的字符串为str,我们可以通过以下步骤实现所需功能:
1. 定义一个变量i,初始化为0,用于记录首个不为*号的字符的下标。
2. 从字符串的开头开始遍历,如果当前字符为*号,则将i加1;否则跳出循环。
3. 定义一个变量j,初始化为字符串长度减1,用于记录最后一个不为*号的字符的下标。
4. 从字符串的末尾开始遍历,如果当前字符为*号,则将j减1;否则跳出循环。
5. 判断i的值与j的值,如果i大于等于j,则说明字符串全由*号组成,此时返回空串。
6. 假设i的值为m,j的值为n,切片截取字符串str[m:n+1]即为去除前导和后导的字符后的字符串。返回该字符串。
具体代码如下所示:
```python
def fun(str):
i = 0
while i < len(str) and str[i] == '*':
i += 1
j = len(str) - 1
while j >= 0 and str[j] == '*':
j -= 1
if i >= j:
return ''
return str[i:j+1]
```
测试示例:
```python
print(fun("*abc")) # 输出:"abc"
print(fun("****")) # 输出:""
print(fun("a**bc*")) # 输出:"a**bc"
print(fun("*****")) # 输出:""
print(fun("*")) # 输出:""
```
注意:为了方便阅读和理解,示例代码中的变量名已更改。实际编写代码时,应尽量使用具有描述性的变量名,避免使用关键字作为变量名。
规定输入的字符串中只包含字母和*号。请编写函数fun,它的功能是:将字符串中的前导*号全部删除,中间和尾部的*号不删除
。函数接口定义:
void fun(char *s);
函数的输入参数:
char *s:指向输入字符串的指针。
函数的输出参数:
无。
函数的返回值:
无。
例如,对于下面的程序:
#include <stdio.h>
#include <string.h>
void fun(char *s);
int main()
{
char s[100];
gets(s);
fun(s);
printf("%s\n", s);
return 0;
}
如果输入字符串为:
****A*B*C*D****
则输出:
A*B*C*D****
如果输入字符串为:
***A**B**C**D***
则输出:
A**B**C**D***
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)