c++ 取出字符串中特定位置的字符组成新的字符串
时间: 2023-09-07 12:13:43 浏览: 70
你可以使用字符串的下标操作符 `[]` 取出特定位置的字符,然后将它们拼接成一个新的字符串。下面是一个示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello world";
string newStr = "";
int index[] = {0, 6, 7, 8, 10}; // 要取出的字符的位置
for (int i = 0; i < 5; i++) {
newStr += str[index[i]];
}
cout << newStr << endl; // 输出 "hwold"
return 0;
}
```
在这个示例中,我们首先定义了一个字符串 `str`,然后定义了一个整型数组 `index`,数组中存储了要取出的字符的下标。接着,我们遍历数组,使用下标操作符 `[]` 取出特定位置的字符,并将它们拼接成一个新的字符串 `newStr`。最后,我们输出新的字符串 `newStr`。
相关问题
c++将字符串特定位置的字符取出,组成一个新的字符串,注意 取出的字符中包括空格
如果要取出的字符中包括空格,可以使用 `substr()` 函数来获取特定位置的子字符串。下面是一个示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello world";
string newStr = "";
int index[] = {0, 6, 7, 8, 10}; // 要取出的字符的位置
for (int i = 0; i < 5; i++) {
newStr += str.substr(index[i], 1);
}
cout << newStr << endl; // 输出 "hw old"
return 0;
}
```
在这个示例中,我们使用了 `substr()` 函数来获取特定位置的子字符串,并将子字符串的第一个字符添加到新的字符串 `newStr` 中。需要注意的是,`substr()` 函数的第一个参数是子字符串的起始位置,第二个参数是子字符串的长度,这里我们取的是长度为 1 的子字符串。
同样的,我们遍历数组,使用 `substr()` 函数获取特定位置的子字符串,并将子字符串的第一个字符添加到新的字符串 `newStr` 中。最后,我们输出新的字符串 `newStr`。
c++如何反转字符串中特定长度的字符
抱歉,我可以回答这个问题。可以用一个循环,每次取出指定长度的子字符串,将其反转后再拼接回原字符串即可。以下是示例代码:
```
def reverse_substring(string, start, length):
end = start + length - 1
substring = string[start:end+1]
reversed_substring = substring[::-1]
return string[:start] + reversed_substring + string[end+1:]
string = "abcdefg"
start = 1
length = 3
result = reverse_substring(string, start, length)
print(result)
```
输出结果为:``aebcdfg``。