string.at
时间: 2023-11-26 22:03:34 浏览: 39
string.at() 是 C++ STL 中 string 类的成员函数,用于访问字符串中指定位置的字符。它的语法为:
```
char& at (size_t pos);
const char& at (size_t pos) const;
```
其中,第一个版本返回一个指向字符串中位置为 pos 的字符的引用,可以用于修改该字符;第二个版本返回一个指向不可修改的字符的 const 引用。
如果 pos 超出了字符串的范围,这两个版本都会抛出 std::out_of_range 异常。与 string[] 运算符相比,at() 更安全,因为它会检查索引是否越界。
相关问题
string.assign
The `string.assign()` function is used to assign a new value to a string. It can be used to replace the entire contents of the string or a portion of it.
Syntax: `string.assign(new_value)`
Example:
```
std::string str = "Hello World!";
str.assign("Goodbye");
// str is now "Goodbye"
str.assign("Hello World!", 5, 5);
// str is now "World"
```
In the first example, the entire contents of the string are replaced with the new value "Goodbye". In the second example, only a portion of the string starting at index 5 and with a length of 5 characters ("World") is replaced with the new value.
String.substring
The String.substring() method is used to extract a portion of a string and returns a new string. It takes two parameters: the starting index and the ending index. The starting index is the position at which the extraction should begin (inclusive), and the ending index is the position at which the extraction should end (exclusive). If the ending index is not provided, the substring will include all characters from the starting index to the end of the string.
Syntax:
string.substring(startIndex, endIndex)
Example:
let str = "Hello World";
let substr1 = str.substring(0,5); // "Hello"
let substr2 = str.substring(6); // "World"