6、 定义函数findall,要求返回符合要求的所有位置的起始下标,如字符串"helloworldhellopythonhelloc++hellojava"需要找出里面所有的"hello"的位置,返回的格式是一个元组,即:(0,10,21,29)
时间: 2023-05-21 20:04:20 浏览: 103
下面是函数findall的完整代码:
```python
def findall(s, substr):
start = 0
result = []
while True:
index = s.find(substr, start)
if index == -1:
break
result.append(index)
start = index + len(substr)
return tuple(result)
```
这个函数会在指定字符串中查找所有子串出现的位置(起始下标),并将结果以元组的形式返回。例如,对于字符串"helloworldhellopythonhelloc hellojava"和要查找的子串"hello",函数的返回值就是元组(0,10,21,29)。
相关问题
c语言编写函数找出字符串中的所有数字,要求区分正负数
以下是一个简单的 C 语言函数,可以找出字符串中的所有数字并区分正负数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void find_numbers(char* str) {
char* p = str;
int num;
while (*p) {
if (isdigit(*p) || ((*p == '+' || *p == '-') && isdigit(*(p+1)))) {
num = strtol(p, &p, 10);
printf("%d\n", num);
} else {
p++;
}
}
}
int main() {
char str[] = "The quick brown -12 fox +34 jumps -56 over 78 the lazy dog.";
find_numbers(str);
return 0;
}
```
这个函数使用了 `isdigit` 函数来判断字符是否是数字,使用了 `strtol` 函数来将字符串转换为整数。在判断到正负数符号时需要检查后面一个字符是否为数字,以区分正负数。
java 返回两个字符串的函数怎么定义
你可以定义一个函数,使用Java的方法返回两个字符串。有几种方法可以实现这个目标,其中一种比较常用的方式是使用Java中的数组或者集合(List)来存储两个字符串,然后将它们作为函数的返回值返回。以下是一个示例函数的定义:
```java
public String[] getTwoStrings() {
String[] result = new String[2];
result[0] = "string1";
result[1] = "string2";
return result;
}
```
这个函数返回一个包含两个字符串的数组。你也可以使用其他的数据结构,例如List,来存储这两个字符串。下面是一个使用List来返回两个字符串的示例函数定义:
```java
public List<String> getTwoStrings() {
List<String> list = new ArrayList<String>();
list.add("string1");
list.add("string2");
return list;
}
```
这个函数返回一个包含两个字符串的List对象。无论你使用数组还是集合,都可以通过返回一个包含多个元素的数据结构来实现返回多个字符串的函数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)