用c语言写一个程序,删除一个字符串里前导的*和尾部的*
时间: 2024-03-23 16:37:59 浏览: 17
好的,以下是用C语言实现删除字符串前导和尾部的*的程序:
```c
#include<stdio.h>
#include<string.h>
void remove_star(char *str)
{
int i, j, len;
// 删除前导的*
while (*str == '*')
{
str++;
}
// 删除尾部的*
len = strlen(str);
for (i = len - 1; i >= 0; i--)
{
if (str[i] != '*')
{
break;
}
}
str[i + 1] = '\0';
// 输出结果
printf("%s", str);
}
int main()
{
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
remove_star(str);
return 0;
}
```
程序中的 `remove_star` 函数用于删除字符串前导和尾部的*。在函数中,先用循环删除前导的*,然后从字符串末尾开始找,找到第一个不是*的字符,将其后面的字符全部置为'\0',这样就删除了尾部的*。最后输出结果即可。
注意,在输入字符串时,要保证字符串长度不超过数组的长度,否则可能会发生越界访问的错误。
相关问题
c语言删除字符串前导和尾部的*
你可以使用以下函数删除字符串前导和尾部的 "*":
```c
#include <stdio.h>
#include <string.h>
void trim(char *str) {
int len = strlen(str);
int start = 0, end = len - 1;
// 删除前导 "*"
while (start < len && str[start] == '*') {
start++;
}
// 删除尾部 "*"
while (end >= 0 && str[end] == '*') {
end--;
}
// 移动字符串
if (start > 0) {
memmove(str, str + start, len - start + 1);
}
// 删除尾部 "*"
if (end < len - 1) {
str[end + 1] = '\0';
}
}
int main() {
char str[] = "***hello***world***";
trim(str);
printf("%s\n", str); // 输出 "hello***world"
return 0;
}
```
这个函数首先使用两个 while 循环分别删除字符串的前导和尾部的 "*",然后使用 memmove 函数将字符串向左移动,最后将尾部的 "*" 替换为 '\0',从而完成删除操作。
C语言:将字符串中的前导*号全部移到字符串的尾部。
可以使用指针来实现该功能,具体步骤如下:
1. 定义指向该字符串的指针,使用char类型指针。
2. 遍历字符串,找到第一个不是*号的字符的位置,记录下来。
3. 将指针移动到该位置。
4. 继续遍历字符串,将所有的*号移到字符串的尾部。
5. 在字符串的末尾添加一个空字符'\0',表示字符串的结束。
下面是实现该功能的C语言代码片段:
```c
void move_star(char* str) {
char* p = str; // 定义指向该字符串的指针
while (*p == '*') { // 找到第一个不是*号的字符的位置
p++;
}
char* q = p; // 将指针移动到该位置
while (*p != '\0') { // 遍历字符串
if (*p != '*') { // 如果当前字符不是*号
*q = *p; // 将当前字符移到非*号的字符的后面
q++;
}
p++;
}
while (*q != '\0') { // 将剩余的*号移到字符串的尾部
*q = '*';
q++;
}
*q = '\0'; // 在字符串的末尾添加一个空字符
}
```
可以使用以下代码进行测试:
```c
int main() {
char str[] = "***hello***world*****";
printf("原字符串:%s\n", str);
move_star(str);
printf("新字符串:%s\n", str);
return 0;
}
```
输出结果为:
```
原字符串:***hello***world*****
新字符串:hello***world*******
```