用c语言回答以下问题,编写一个函数删除字符串中指定字符
时间: 2023-07-16 11:15:12 浏览: 58
以下是使用C语言编写的删除字符串中指定字符的函数:
```c
void delete_char(char s[], char c) {
int i, j;
for (i = 0; s[i] != '\0'; i++) {
if (s[i] == c) {
for (j = i; s[j] != '\0'; j++) {
s[j] = s[j + 1];
}
i--;
}
}
}
```
该函数接受两个参数:一个字符串s和一个字符c。它遍历字符串s中的每个字符,如果找到字符c,则将其从字符串中删除。它通过将后面的字符向前移动一个位置来实现删除。
例如,如果我们有字符串s = "hello world",并且要删除字符l,则调用函数delete_char(s, 'l')会将字符串s更改为"heo word"。
相关问题
用c语言编写一个函数,删除字符串s中的特殊字符ch
好的,以下是用 C 语言编写一个函数,删除字符串 s 中的特殊字符 ch 的代码:
```
#include <stdio.h>
#include <string.h>
void remove_char(char *s, char ch) {
int i, j;
int n = strlen(s);
for (i = 0, j = 0; i < n; i++) {
if (s[i] != ch) {
s[j] = s[i];
j++;
}
}
s[j] = '\0';
}
int main() {
char s[100], ch;
printf("请输入一个字符串: ");
scanf("%s", s);
getchar(); // 消耗掉回车符
printf("请输入要删除的特殊字符: ");
scanf("%c", &ch);
remove_char(s, ch);
printf("删除特殊字符后的字符串为: %s\n", s);
return 0;
}
```
不要忘记在调用 scanf 函数后,消耗掉输入的回车符,否则可能导致后续 fgets 函数和 gets 函数等读取空白行的问题。
用c语言编写一个函数把字符串中内容逆置
以下是使用 C 语言编写的函数,将输入字符串逆置:
```c
#include <stdio.h>
#include <string.h>
void reverseString(char str[]) {
int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - 1 - i];
str[len - 1 - i] = temp;
}
}
int main() {
char str[] = "hello world";
printf("Original string: %s\n", str);
reverseString(str);
printf("Reversed string: %s\n", str);
return 0;
}
```
该代码中,`reverseString` 函数接收一个字符数组 `str`,并使用循环将字符串中的内容逆置。`main` 函数中定义了一个字符串 `str`,并输出原字符串及逆置后的字符串。
相关推荐
![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)