编写一个程序,有一个字符串,请查找第一次和最后一次出现I的位置,c语言
时间: 2024-06-04 11:13:29 浏览: 9
好的,这是一个关于字符串操作的问题。以下是c语言程序代码,实现查找第一次和最后一次出现I的位置:
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int i, first = -1, last = -1;
printf("请输入一个字符串:\n");
gets(str);
for(i = 0; i < strlen(str); i++)
{
if(str[i] == 'I')
{
if(first == -1)
first = i;
last = i;
}
}
if(first == -1)
printf("字符串中没有出现过I。\n");
else
printf("第一次出现I的位置是:%d,最后一次出现I的位置是:%d。\n", first, last);
return 0;
}
希望能够帮到您。
相关问题
编写一个程序,有一个字符串,请查找第一次和最后一次出现I的位置c语言
好的,这是一个关于字符串操作的问题。在C语言中,可以使用strchr()函数来查找字符串中第一次出现某个字符的位置,使用strrchr()函数来查找字符串中最后一次出现某个字符的位置。以下是示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "I love China and its people.";
char *ptr1, *ptr2;
ptr1 = strchr(str, 'I');
ptr2 = strrchr(str, 'I');
if (ptr1 == NULL || ptr2 == NULL) {
printf("未找到字符'I'\n");
} else {
printf("第一次出现字符'I'的位置为:%ld\n", ptr1 - str);
printf("最后一次出现字符'I'的位置为:%ld\n", ptr2 - str);
}
return 0;
}
```
输出结果为:
```
第一次出现字符'I'的位置为:0
最后一次出现字符'I'的位置为:9
```
希望这个代码能够解决你的问题,如果还有其它问题,请继续提问。
编写函数求某字符在字符串中第一次出现的位置用c语言
可以使用C语言的标准库函数`strchr()`来实现。`strchr()`函数的原型为:
```c
char *strchr(const char *s, int c);
```
该函数在字符串`s`中查找字符`c`第一次出现的位置,并返回该位置的指针。如果未找到该字符,则返回`NULL`指针。
以下是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
char ch = 'o';
char *pos = strchr(str, ch);
if (pos != NULL) {
printf("'%c' first appears at position %d\n", ch, pos - str);
} else {
printf("'%c' not found in string\n", ch);
}
return 0;
}
```
输出结果为:
```
'o' first appears at position 4
```
注意,`pos - str`表示`pos`指针相对于字符串起始地址`str`的偏移量,即字符在字符串中的位置。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)