编写程序对输入的字符串进行处理,去掉首尾的空格。 使用c++
时间: 2024-03-07 08:46:41 浏览: 26
下面是一个简单的 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++的字符串库函数`trim`去掉字符串首尾空格,示例代码如下:
```c++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str = " hello world ";
str.erase(str.begin(), find_if(str.begin(), str.end(), [](int ch) {
return !isspace(ch);
}));
str.erase(find_if(str.rbegin(), str.rend(), [](int ch) {
return !isspace(ch);
}).base(), str.end());
cout << "去掉首尾空格后的字符串为:" << str << endl;
return 0;
}
```
输出结果为:
```
去掉首尾空格后的字符串为:hello world
```
掉字符串首尾空格c++
可以使用C++中的字符串处理函数`std::string::find_first_not_of`和`std::string::find_last_not_of`来去除字符串的首尾空格。
示例代码:
```c++
#include <iostream>
#include <string>
int main() {
std::string str = " hello world! ";
size_t start = str.find_first_not_of(" ");
size_t end = str.find_last_not_of(" ");
if (start == std::string::npos || end == std::string::npos) {
std::cout << "Error: string is all spaces\n";
return 1;
}
std::string trimmed_str = str.substr(start, end - start + 1);
std::cout << trimmed_str << std::endl; // output: "hello world!"
return 0;
}
```
在上述代码中,`std::string::find_first_not_of`和`std::string::find_last_not_of`函数分别查找第一个非空格字符和最后一个非空格字符的位置。如果字符串全部为空格,则这两个函数的返回值都是`std::string::npos`,表示查找失败。如果字符串不全是空格,则使用`std::string::substr`函数提取出去除空格后的子字符串。