string去除前置空格
时间: 2023-07-21 12:38:50 浏览: 47
可以使用trim函数去除string前后的空格,具体实现代码如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = " hello world";
str = str.erase(0, str.find_first_not_of(" "));
cout << str << endl;
return 0;
}
```
输出结果为:`hello world`
相关问题
csharp的string去除所有空格
你可以使用 C# 的 `Replace` 方法和空格字符 `" "` 来去除字符串中所有的空格。示例代码如下:
```csharp
string str = " This is a string with spaces. ";
str = str.Replace(" ", "");
Console.WriteLine(str); // 输出:Thisisastringwithspaces.
```
另外,如果你想去除字符串中的其他空白字符(如制表符 `\t` 和换行符 `\n` 等),可以使用 `Trim()` 方法。示例代码如下:
```csharp
string str = "\tThis is a \n string with spaces. ";
str = str.Trim();
Console.WriteLine(str); // 输出:This is a string with spaces.
```
string自带去除空格函数
在Python中,string类型的strip()函数可以用于去除字符串两端的空格。例如:
```
str = " hello world "
new_str = str.strip()
print(new_str) # 输出 "hello world"
```
此外,还可以使用lstrip()函数和rstrip()函数分别去除字符串左侧和右侧的空格。