输入字符串(长度大于2),删除首尾两个字符,输出结果字符串的c++代码
时间: 2023-04-10 19:03:58 浏览: 119
以下是Lua语言的代码实现:
```lua
local str = "example"
str = string.sub(str, 2, -2)
print(str)
```
这段代码可以删除字符串的首尾两个字符,输出结果为 "xampl"。
相关问题
编写程序对输入的字符串进行处理,去掉首尾的空格。 使用c++
下面是一个简单的 C++ 程序,用于从标准输入读取字符串,并去除其首尾空格。
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
getline(cin, s); // 从标准输入读取字符串
// 去除首尾空格
int i = 0, j = s.length() - 1;
while (i < s.length() && s[i] == ' ') i++;
while (j >= 0 && s[j] == ' ') j--;
s = s.substr(i, j - i + 1);
cout << s << endl; // 输出处理后的字符串
return 0;
}
```
以上程序中,我们使用了 `getline` 函数从标准输入读取一行字符串,然后使用两个指针 `i` 和 `j` 分别指向字符串的头和尾,循环移动指针直到它们指向一个非空格字符,然后使用 `substr` 函数从字符串中提取出去掉空格后的部分。最后输出结果即可。
掉字符串首尾空格c++
可以使用C++中的字符串库函数`std::string::find_first_not_of`和`std::string::find_last_not_of`来完成去掉首尾空格的操作。具体实现如下:
```c++
#include <iostream>
#include <string>
using namespace std;
string trim(string s) {
size_t start = s.find_first_not_of(" ");
size_t end = s.find_last_not_of(" ");
return s.substr(start, end - start + 1);
}
int main() {
string s = " hello world ";
string result = trim(s);
cout << result << endl; // 输出 "hello world"
return 0;
}
```
在上面的代码中,`trim`函数接受一个字符串参数`s`,并返回去掉首尾空格后的字符串。`find_first_not_of`函数用来查找第一个不是空格的字符的位置,`find_last_not_of`函数用来查找最后一个不是空格的字符的位置,然后我们使用`substr`函数从`start`位置开始,长度为`end - start + 1`的子串作为结果返回。