编写函数getPositions(string, subStr),返回string中出现子串subStr的位置构成的数组
时间: 2024-02-28 08:57:40 浏览: 18
好的,我可以为您编写这个函数。以下是Python语言的实现:
```python
def getPositions(string, subStr):
positions = []
start = 0
while True:
start = string.find(subStr, start)
if start == -1:
break
positions.append(start)
start += 1
return positions
```
这个函数使用了字符串的find方法来找到子串在字符串中的位置,并且使用一个while循环来找到所有的位置。如果字符串中没有子串,那么返回一个空数组。
相关问题
string substr函数
string的substr函数是用于截取字符串的子串的函数。它接受两个参数,第一个参数是起始位置,第二个参数是要截取的子串的长度(可选)。如果只传入一个参数,则默认截取从起始位置到字符串末尾的所有字符。
下面是一个示例:
```
string str = "Hello, World!";
string sub = str.substr(7, 5);
```
在上面的示例中,str.substr(7, 5)将返回"World",因为它从索引位置7开始截取长度为5的子串。
如果只传入一个参数,比如str.substr(7),则将返回"World!",因为它从索引位置7开始截取到字符串末尾的所有字符。
需要注意的是,substr函数返回的是一个新的字符串,原始字符串并不会被修改。
编写一个C++函数用来查找一个字符串中某子串的位置并返回该位置
以下是一个简单的C++函数,用于在一个字符串中查找某个子串的位置,并返回该位置。如果找不到子串,则返回-1。
```cpp
#include <iostream>
#include <string>
using namespace std;
int findSubstringPosition(string str, string subStr)
{
size_t pos = str.find(subStr);
if (pos != string::npos) {
return pos;
}
else {
return -1;
}
}
int main()
{
string str = "Hello, World!";
string subStr = "World";
int pos = findSubstringPosition(str, subStr);
if (pos != -1) {
cout << "The substring was found at position " << pos << endl;
}
else {
cout << "The substring was not found in the string" << endl;
}
return 0;
}
```
在这个例子中,我们定义了一个名为`findSubstringPosition`的函数,它接收两个参数:`str`和`subStr`。函数使用`find`方法在`str`中查找`subStr`,并将结果存储在`pos`变量中。如果`pos`不等于`string::npos`,则表示找到了子串并返回其位置。否则,函数返回-1。在主函数中,我们调用了这个函数,并根据返回值输出相应的结果。
相关推荐
![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)