用c语言实现查找字符串中所有指定的字符要求编写一个实现输出字符串s中值等于字符ch的所有字符的函数,并用主函数测试结果。输入格式: 输入有2行,第一行是一个字符x,表示需要查找的字符;第二行是一个以回车结束的非空字符串(不超过100个字符)。 输出格式: 输出所有查找到的字符的下标(从0开始),每个数之间隔1个空格,行末不留空格,如果查找不到,输出-1。
时间: 2023-06-14 21:04:36 浏览: 120
以下是用C语言实现查找字符串中所有指定的字符的代码:
```c
#include <stdio.h>
#include <string.h>
void find_char(char ch, char *s) {
int len = strlen(s);
int found = 0;
for (int i = 0; i < len; i++) {
if (s[i] == ch) {
printf("%d ", i);
found = 1;
}
}
if (!found) {
printf("-1");
}
}
int main() {
char ch, s[100];
scanf("%c", &ch);
scanf("%s", s);
find_char(ch, s);
return 0;
}
```
主函数中首先读入需要查找的字符 `ch` 和字符串 `s`,然后调用 `find_char` 函数进行查找。 `find_char` 函数遍历整个字符串 `s`,如果找到与 `ch` 相等的字符,就输出它的下标。如果没有找到,就输出 `-1`。
相关问题
编写算法删除字符串s中值等于ch(变量名)的所有字符,用c语言实现
好的,我了解了您的要求。下面是C语言实现删除字符串s中值等于ch的所有字符的代码:
```c
#include <stdio.h>
#include <string.h>
void removeChar(char *s, char ch) {
int len = strlen(s);
int j = 0;
for (int i = 0; i < len; i++) {
if (s[i] != ch) {
s[j] = s[i];
j++;
}
}
s[j] = '\0';
}
int main() {
char s[100];
char ch;
printf("请输入字符串: ");
fgets(s, 100, stdin);
printf("请输入要删除的字符: ");
scanf("%c", &ch);
removeChar(s, ch);
printf("删除后的字符串为: %s\n", s);
}
```
您可以将要删除的字符串存储在字符数组s中,将要删除的字符存储在char类型的变量ch中。函数removeChar()将遍历字符串s中的每个字符,如果字符不等于ch,则将其存储在原始字符串的位置。最后用'\0'结束字符串。
编写算法删除字符串s中值等于ch(变量名)的第一个字符,用c语言实现
可以使用以下代码实现:
```c
#include <stdio.h>
#include <string.h>
void remove_char(char s[], char ch) {
int len = strlen(s);
int i, j;
for (i = 0; i < len; i++) {
if (s[i] == ch) {
for (j = i; j < len - 1; j++) {
s[j] = s[j + 1];
}
s[len - 1] = '\0';
break;
}
}
}
int main() {
char s[] = "Hello world";
char ch = 'l';
remove_char(s, ch);
printf("%s", s);
return 0;
}
```
这段代码中,我们想要删除字符串 `s` 中第一个出现值等于 `ch` 的字符。我们先计算字符串的长度 `len`,然后使用 `for` 循环遍历字符串。如果遇到了一个值等于 `ch` 的字符,我们会使用另一个 `for` 循环,将字符串 `s` 中这个字符后面的所有字符往前移一位,覆盖掉这个字符。最后,我们在字符串末尾加上一个结尾符,以便正确显示新的字符串。
需要注意的是,为了保证程序的健壮性,我们还应该检查字符 `ch` 是否在字符串中出现。如果 `ch` 没有出现在字符串中,我们应该采取一些特殊的处理方式。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)