编写一个函数,除了字符串前导的*号之外,将串中的其他*号全部删除
时间: 2024-03-27 07:35:46 浏览: 22
好的,以下是 Python 代码实现:
```python
def remove_stars(s):
"""
除了字符串前导的*号之外,将串中的其他*号全部删除
"""
if not s:
return ""
# 找到第一个非*字符的位置
i = 0
while i < len(s) and s[i] == '*':
i += 1
# 从第一个非*字符开始遍历,将后面的*号删除
res = s[:i]
for j in range(i, len(s)):
if s[j] != '*':
res += s[j]
elif j == i or s[j-1] != '*':
res += '*'
return res
```
这个函数的基本思路是:先找到第一个非*字符的位置,然后从这个位置开始遍历整个字符串,将后面的*号删除,并保留连续的*号中的第一个。最后返回删除后的字符串。
需要注意的是,如果字符串本身就是空串,或者只包含*号,那么函数返回空串。
相关问题
编写函数将字符串中的前导*号全部移到字符串的尾部。用c语音
下面是一个将字符串中前导星号移动到字符串尾部的 C 语言函数实现:
```c
#include <stdio.h>
#include <string.h>
void move_star_to_end(char *str) {
int len = strlen(str);
int i, j;
// 找到第一个非星号字符的下标
for (i = 0; i < len && str[i] == '*'; i++) {}
// 将非星号字符移动到字符串开头
for (j = i; j < len; j++) {
if (str[j] != '*') {
str[i++] = str[j];
}
}
// 将剩余的位置填充星号
while (i < len) {
str[i++] = '*';
}
}
int main() {
char str[] = "***hello***world*";
move_star_to_end(str);
printf("%s\n", str);
return 0;
}
```
以上代码中,我们首先使用 `strlen` 函数获取字符串的长度,然后使用两个循环将字符串中的星号移动到末尾。具体来说,第一个循环将指针 `i` 移动到第一个非星号字符的位置,第二个循环将非星号字符移动到字符串的开头,最后一个循环将剩余的位置填充星号。
编写函数将字符串中的前导*号全部移到字符串的尾部.请用C语言回答。
下面是一个将字符串中的前导 "*" 全部移到字符串尾部的函数示例:
```c
#include <stdio.h>
#include <string.h>
void move_star_to_end(char* str) {
int len = strlen(str);
int i, j;
// 找到第一个非 * 字符的位置
i = 0;
while (str[i] == '*') {
i++;
}
// 将前导 * 移到尾部
for (j = i; j < len; j++) {
if (str[j] != '*') {
str[i++] = str[j];
}
}
for (; i < len; i++) {
str[i] = '*';
}
}
int main() {
char str[] = "***hello**world***";
move_star_to_end(str);
printf("%s\n", str);
return 0;
}
```
输出结果为:
```
helloworld******
```
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)