c++用指针编写删除字符串所有尾部空格
时间: 2024-04-16 20:28:58 浏览: 28
您好!以下是使用指针删除字符串尾部空格的C++代码示例:
```c++
#include <iostream>
#include <cstring>
void removeTrailingSpaces(char* str) {
int len = strlen(str);
char* end = str + len - 1;
while (end >= str && *end == ' ') {
*end = '\0';
end--;
}
}
int main() {
char str[] = "Hello, World! ";
std::cout << "Before: " << str << std::endl;
removeTrailingSpaces(str);
std::cout << "After: " << str << std::endl;
return 0;
}
```
在上面的代码中,`removeTrailingSpaces` 函数使用指针 `end` 来追踪字符串末尾的字符,然后从末尾开始逐个检查字符是否为空格,如果是,则将其设置为 null 终止字符 '\0',直到遇到第一个非空格字符为止。最后,函数将删除多余的尾部空格。
希望这可以帮助您!如果您还有其他问题,请随时提问。
相关问题
用指针编写删除字符串所有尾部空格
当然,下面是使用指针删除字符串所有尾部空格的C++代码示例:
```c++
#include <iostream>
void removeTrailingSpaces(char* str) {
if (str == nullptr) {
return;
}
char* end = str;
while (*end != '\0') {
end++;
}
end--;
while (end >= str && *end == ' ') {
*end = '\0';
end--;
}
}
int main() {
char str[] = "Hello, World! ";
std::cout << "Before: " << str << std::endl;
removeTrailingSpaces(str);
std::cout << "After: " << str << std::endl;
return 0;
}
```
在上述代码中,`removeTrailingSpaces` 函数首先检查传入的字符串指针是否为 `nullptr`,以处理空指针的情况。然后,使用一个指针 `end` 将其移动到字符串末尾的最后一个字符。接下来,从末尾开始,如果遇到空格字符,则将其替换为 null 终止字符 '\0',直到遇到第一个非空格字符为止。
希望这对您有所帮助!如果您有任何其他问题,请随时提问。
掉字符串首尾空格c++ 用指针
可以使用指针来去掉字符串首尾的空格,具体实现如下:
```c++
#include <iostream>
#include <cstring>
using namespace std;
void trim(char* str) {
if (str == nullptr) {
return;
}
// 去掉字符串前面的空格
char* start = str;
while (*start == ' ') {
start++;
}
// 去掉字符串后面的空格
char* end = start + strlen(start) - 1;
while (end > start && *end == ' ') {
end--;
}
*(end + 1) = '\0';
// 拷贝去掉空格后的字符串到原字符串
if (start != str) {
strcpy(str, start);
}
}
int main() {
char str[] = " hello world ";
trim(str);
cout << str << endl; // 输出 hello world
return 0;
}
```
在该代码中,首先定义了一个 `trim` 函数,该函数通过指针遍历字符串,去掉字符串前面和后面的空格,并将去掉空格后的字符串拷贝回原字符串中。最后,在 `main` 函数中测试了一下该函数的功能。