c语言编程实现:从键盘输入一个字符,找出该字符在已知字符串“Hello,world!”中第一次出现的位置。若不在该字符串中,则打印“该字符不在已知字符串中”。
时间: 2024-05-02 17:19:29 浏览: 25
可以直接使用C语言的库函数strstr来实现字符串查找,代码如下:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "Hello,world!";
char ch;
char *ptr;
printf("请输入一个字符:");
scanf("%c", &ch);
ptr = strstr(str, &ch);
if (ptr == NULL)
{
printf("该字符不在已知字符串中\n");
}
else
{
printf("该字符在已知字符串中的位置是:%ld\n", ptr - str);
}
return 0;
}
```
当输入字符'o'时,输出结果为:
```
请输入一个字符:o
该字符在已知字符串中的位置是:4
```
当输入字符'x'时,输出结果为:
```
请输入一个字符:x
该字符不在已知字符串中
```
笑话:有一天,一个程序员在睡觉时梦见自己变成了一段代码,于是他醒了过来,打开电脑,发现自己真的变成了一段代码。
相关问题
已知一个字符串s 设计一个算法来统计 s中字符出现的次数 用c语言编写
可以使用一个数组来存储每个字符出现的次数,遍历字符串s,对于s中的每个字符,将其对应的数组值加1。代码如下:
```c
#include <stdio.h>
#include <string.h>
void count_chars(char *s, int *count) {
int len = strlen(s);
for (int i = 0; i < len; i++) {
count[s[i]]++;
}
}
int main() {
char s[] = "Hello, world!";
int count[256] = {0};
count_chars(s, count);
for (int i = 0; i < 256; i++) {
if (count[i] > 0) {
printf("%c: %d\n", i, count[i]);
}
}
return 0;
}
```
输出结果为:
```
!: 1
,: 1
H: 1
e: 1
l: 3
o: 2
r: 1
w: 1
d: 1
```
注意,这个算法只能统计ASCII码中的字符,如果需要支持Unicode字符,需要使用更复杂的算法。
已知字符串subStr为str的子串,在母串中找出subStr,在其前面插入一个@字符,需保持子串内容完整性使用c语言
实现如下:
```c
#include <stdio.h>
#include <string.h>
void insertAt(char *str, char *subStr) {
char *p = strstr(str, subStr); // 查找子串
if (p != NULL) {
int len = strlen(subStr); // 计算子串长度
int index = p - str; // 计算子串在母串中的索引位置
char tmp[100] = {0}; // 临时存储插入@字符后的母串
strncpy(tmp, str, index); // 将子串前面的部分复制到临时变量中
tmp[index] = '@'; // 插入@字符
strncpy(tmp + index + 1, str + index, len); // 将子串复制到临时变量中
strcpy(tmp + index + len + 1, str + index + len); // 将子串后面的部分复制到临时变量中
strcpy(str, tmp); // 将临时变量中的字符串复制回原来的字符串中
}
}
int main() {
char str[100] = "hello world!";
char subStr[10] = "world";
insertAt(str, subStr);
printf("%s\n", str); // 输出:hello @world!
return 0;
}
```