C语言编写一个函数输入一个字符串,将字符 串中的*全部移动到字符串的尾部...

可以使用如下代码实现:int len = strlen(str); int i, j; for(i=0, j=0; i<len; i++) { if(str[i] != '') { str[j] = str[i]; j++; } } str[j] = '\0'; for(i=j; i<len; i++) { if(str[i] == '') { str[j] = '*'; j++; } }

### 回答1: 可以使用如下代码实现:int len = strlen(str); int i, j; for(i=0, j=0; i<len; i++) { if(str[i] != '*') { str[j] = str[i]; j++; } } str[j] = '\0'; for(i=j; i<len; i++) { if(str[i] == '*') { str[j] = '*'; j++; } } ### 回答2: 可以编写一个函数,实现输入一个字符串,将字符串中的*全部移动字符串尾部。具体步骤如下: 1. 首先定义一个函数,接收一个字符串作为参数。 2. 创建一个新的字符串,用于存储移动后的结果。 3. 使用一个循环遍历原字符串中的每个字符。 4. 判断当前字符是否为*,如果是*则将其放到新的字符串尾部。 5. 不是*的字符则直接放到新的字符串中。 6. 最后返回移动后的新字符串。 以下是示例代码: ```c #include <stdio.h> void moveStarsToEnd(char* str) { // 创建一个新的字符串,用于存储移动后的结果 char new_str[100]; int count = 0; // 遍历原字符串中的每个字符 for (int i = 0; str[i] != '\0'; i++) { // 判断当前字符是否为* if (str[i] == '*') { // 将*放到新的字符串尾部 new_str[count] = str[i]; count++; } } // 将剩余的字符放到新的字符串中 for (int i = 0; str[i] != '\0'; i++) { if (str[i] != '*') { new_str[count] = str[i]; count++; } } // 添加字符串结束符 new_str[count] = '\0'; // 打印移动后的字符串 printf("移动后的字符串:%s\n", new_str); } int main() { char str[100]; // 输入字符串 printf("请输入字符串:"); scanf("%s", str); // 调用移动函数 moveStarsToEnd(str); return 0; } ``` 通过以上函数,我们可以实现输入一个字符串,并将其中的*全部移动字符串尾部。例如,输入字符串"ab*c*def*g",则移动后的字符串为"abcdefg**"。 ### 回答3: 下面是一个C语言编写函数,实现将字符串中的*全部移动字符串尾部: ```c #include <stdio.h> #include <string.h> void moveCharToEnd(char *str) { int len = strlen(str); int count = 0; // 统计字符串中的*的个数 for (int i = 0; i < len; i++) { if (str[i] == '*') { count++; } } // 将字符串中的非*字符移到前面 int index = 0; for (int i = 0; i < len; i++) { if (str[i] != '*') { str[index] = str[i]; index++; } } // 在字符串末尾添加*的个数个* for (int i = 0; i < count; i++) { str[index] = '*'; index++; } // 字符串末尾添加结束符 str[index] = '\0'; } int main() { char str[100]; printf("请输入字符串:"); scanf("%s", str); moveCharToEnd(str); printf("移动后的字符串: %s\n", str); return 0; } ``` 这段代码首先计算字符串中的*的个数,然后将字符串中的非*字符移到字符串的前面,最后在字符串的末尾添加*的个数个*。接着在主函数输入一个字符串,调用moveCharToEnd函数进行移动操作,并打印移动后的字符串
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值