查找字符串中所有指定的字符
时间: 2024-05-05 21:22:53 浏览: 7
可以使用循环和条件语句遍历字符串中的每个字符,如果字符与指定字符相等,则将其加入到一个新的字符串中。以下是一个示例 Python 代码:
```python
def find_chars(string, char):
result = ""
for s in string:
if s == char:
result += s
return result
```
这个函数名为 `find_chars`,接受两个参数:一个字符串 `string` 和一个字符 `char`,返回一个新的字符串,其中包含所有与指定字符相等的字符。你可以像下面这样调用它:
```python
string = "hello world"
char = "l"
result = find_chars(string, char)
print(result)
```
这将输出字符串 `lll`,因为原始字符串中有三个字母 `l`。
相关问题
python怎么查找字符串中所有指定字符
可以使用Python内置的字符串方法find()或者re模块中的search()方法来查找字符串中所有指定字符。
方法一:使用find()方法
find()方法可以在字符串中查找指定字符,并返回字符首次出现的索引值。如果要查找所有指定字符,可以使用一个循环来遍历字符串,直到字符串中没有指定字符为止。
下面是一个示例代码:
```python
string = "hello world"
char = "l"
index = -1
while True:
index = string.find(char, index + 1)
if index == -1:
break
print(index)
```
输出结果为:
```
2
3
9
```
方法二:使用re模块中的search()方法
re模块中的search()方法可以通过正则表达式查找字符串中所有指定字符。下面是一个示例代码:
```python
import re
string = "hello world"
char = "l"
pattern = re.compile(char)
result = pattern.finditer(string)
for r in result:
print(r.start())
```
输出结果与上面的示例代码相同。
查找字符串中所有指定的字符C语言
可以使用C语言中的字符串操作函数strchr()来查找字符串中所有指定的字符。
strchr()函数的原型为:
```c
char *strchr(const char *s, int c);
```
其中,第一个参数s是要查找的字符串,第二个参数c是要查找的字符。
该函数会返回指向第一次出现字符c的位置的指针,如果没有找到,返回NULL。
我们可以通过循环调用strchr()函数来查找字符串中所有指定的字符,如下所示:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello world";
char target = 'l';
char *pos = str;
while ((pos = strchr(pos, target)) != NULL) {
printf("Found at position %d\n", pos - str + 1);
pos++;
}
return 0;
}
```
上述代码会输出字符串中所有字母'l'的位置:
```
Found at position 3
Found at position 4
Found at position 10
```
注意,strchr()函数只能查找单个字符,如果要查找多个字符,需要循环调用该函数。