指定位置输出字符串(指针)
时间: 2024-03-10 20:40:29 浏览: 39
以下是一个实现函数match的C语言代码,该函数可以打印出给定字符串中从与第一个字符匹配的位置开始到与第二个字符匹配的位置之间的所有字符,并返回第一个字符的地址:
```c
char *match(char *s, char ch1, char ch2) {
char *p = s;
while (*p != ch1 && *p != '\0') {
p++;
}
while (*p != ch2 && *p != '\0') {
putchar(*p);
p++;
}
putchar(*p);
return p;
}
```
该函数的使用方法如下:
```c
char s[] = "Hello, world!";
char *p = match(s, 'o', 'l');
```
上述代码将会输出"o, worl",并且p指向字符串中第一个字符'l'的地址。
相关问题
C输出字符串中指定字符的位置
你可以使用C语言的字符串函数来实现输出字符串中指定字符的位置。以下是一个示例代码,其中使用了字符串函数strchr()来查找指定字符的位置:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[50], ch;
printf("Enter a string: ");
fgets(str, 50, stdin);
printf("Enter the character to search: ");
scanf("%c", &ch);
char *pos = strchr(str, ch);
if (pos) {
printf("The character '%c' is found at position %ld\n", ch, pos - str);
} else {
printf("The character '%c' is not found in the string\n", ch);
}
return 0;
}
```
在这个示例代码中,我们首先使用fgets()函数从标准输入读取一个字符串,然后使用scanf()函数读取要查找的字符。接下来,我们使用strchr()函数查找指定字符在字符串中的位置,如果找到了,就输出该位置。注意,strchr()函数返回的是一个指针,我们需要计算该指针和字符串首地址之间的距离,才能得到该字符在字符串中的位置。如果没有找到指定字符,则输出一个提示信息。
c语言输出字符串中指定字符的位置
你可以使用C语言中的字符串处理函数`strchr`来查找某个字符在字符串中第一次出现的位置。该函数的函数原型为:
```c
char *strchr(const char *str, int c);
```
其中,`str`是要查找的字符串,`c`是要查找的字符。
如果找到了该字符,则返回该字符在字符串中第一次出现的位置的指针;如果没找到,则返回`NULL`。
下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[50];
char c;
char *p;
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
printf("请输入要查找的字符:");
scanf("%c", &c);
p = strchr(str, c);
if (p != NULL)
{
printf("字符 %c 在字符串中的位置为:%d\n", c, p - str + 1);
}
else
{
printf("未找到字符 %c\n", c);
}
return 0;
}
```
在上面的代码中,我们先使用`fgets`函数从标准输入中读取一个字符串,然后使用`scanf`函数读取要查找的字符。接着,我们使用`strchr`函数查找该字符在字符串中的位置,并计算出该位置相对于字符串首地址的偏移量,最后输出该偏移量加上1的值,即为字符在字符串中的位置。