c++ 在字符串里查找一个字符
时间: 2023-06-12 19:05:14 浏览: 81
可以使用 C 语言中的 `strchr()` 函数来查找一个字符在字符串中的位置。该函数原型如下:
```c
char *strchr(const char *s, int c);
```
其中,`s` 是要查找的字符串,`c` 是要查找的字符。该函数会在 `s` 中查找字符 `c`,如果找到则返回该字符在 `s` 中的位置指针,否则返回 `NULL`。下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello, world!";
char *p = strchr(str, 'o');
if (p) {
printf("Found: %s\n", p);
} else {
printf("Not found.\n");
}
return 0;
}
```
该代码会在 `str` 中查找字符 `'o'`,并输出找到的位置。运行结果如下:
```
Found: o, world!
```
可以看到,该函数找到了字符 `'o'` 在字符串中的位置,并返回了该位置的指针。
相关问题
c++在字符串中查找字符串的方式
在字符串中查找字符串可以使用以下方法:
1. 使用字符串的find()方法,该方法返回字符串中第一次出现指定字符串的位置,如果没有找到则返回-1。
例如:
```
str = "hello world"
index = str.find("world")
print(index) # 输出 6
```
2. 使用字符串的index()方法,该方法与find()方法类似,但是如果指定字符串不存在则会抛出ValueError异常。
例如:
```
str = "hello world"
try:
index = str.index("world")
print(index) # 输出 6
except ValueError:
print("指定字符串不存在")
```
3. 使用正则表达式进行匹配。
例如:
```
import re
str = "hello world"
pattern = "world"
match = re.search(pattern, str)
if match:
print(match.start()) # 输出 6
```
4. 使用字符串的count()方法统计指定字符串在原字符串中出现的次数。
例如:
```
str = "hello world"
count = str.count("o")
print(count) # 输出 2
```
c++实现在字符串里面查找回文字符串并返回
可以使用双指针的方法来实现在字符串里面查找回文字符串,并返回结果。
具体做法如下:
1. 定义两个指针 i 和 j,分别指向字符串的起始位置和末尾位置。
2. 从 i 和 j 开始,分别向中间移动,判断两个指针所指的字符是否相同,如果不同,则说明当前子串不是回文字符串。
3. 如果两个字符相同,则继续向中间移动,直到 i 和 j 相遇或者子串不是回文字符串为止。
4. 如果当前子串是回文字符串,则将其保存到结果字符串中。
5. 将指针 i 后移一位,重复步骤 2~4,直到 i 到达字符串末尾。
以下是该算法的 C 语言实现:
```c
#include <stdio.h>
#include <string.h>
char* find_palindrome(char *str, int len)
{
char *result = NULL;
int i, j, k;
for (i = 0; i < len; i++) {
for (j = len - 1; j >= i; j--) {
if (str[i] == str[j]) {
for (k = 1; k <= (j - i + 1) / 2; k++) {
if (str[i + k - 1] != str[j - k + 1]) {
break;
}
}
if (k > (j - i + 1) / 2) {
int size = j - i + 2;
result = (char*)malloc(size);
if (result) {
strncpy(result, str + i, size - 1);
result[size - 1] = '\0';
}
return result;
}
}
}
}
return result;
}
int main()
{
char str[] = "abacdfgdcaba";
char *result = find_palindrome(str, strlen(str));
if (result) {
printf("The palindrome is: %s\n", result);
free(result);
} else {
printf("No palindrome found.\n");
}
return 0;
}
```
在这个例子中,我们定义了一个函数 `find_palindrome`,它接受一个字符串和字符串的长度作为参数,返回一个指向回文字符串的指针,如果没有找到回文字符串,则返回 NULL。
我们首先定义了三个指针 i、j 和 k,分别用于遍历字符串和判断回文字符串。然后,我们通过两重循环,依次枚举所有的子串,判断它是否是回文字符串。如果是回文字符串,则将其保存到结果字符串中并返回。
在主函数中,我们调用 `find_palindrome` 函数来查找字符串中的回文字符串,并输出结果。