用C语言编写函数将字符串中的前导*号全部移到字符串的尾部,程序包含指针
时间: 2023-12-05 21:05:25 浏览: 69
好的,可以使用指针实现该函数。下面是一个示例代码:
```c
#include <stdio.h>
void move_star(char *str) {
char *p = str;
char *q = str;
while (*p) {
if (*p != '*') {
*q++ = *p;
}
p++;
}
while (*q) {
*q++ = '*';
}
}
int main() {
char str[] = "***hello*world**";
printf("Original string: %s\n", str);
move_star(str);
printf("Modified string: %s\n", str);
return 0;
}
```
该函数的实现思路是:使用两个指针p和q,初始都指向字符串的首字符。遍历整个字符串,如果p指向的字符不是星号,则将其移动到q指向的位置,并将q向后移动一个位置;否则只将p向后移动一个位置。最后,将q指向的位置及其后面的所有字符都改为星号即可。
注意,此处的字符串是以字符数组的形式传递给函数的,因此需要在函数内部修改该字符数组。如果需要修改传入的字符串,可以将函数参数改为指向字符数组的指针。
相关问题
编写函数将字符串中的前导*号全部移到字符串的尾部.请用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******
```
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*******
```