修剪空间C++指针
Trimming spaces C++ POINTERS
我编写了一个简单的函数来修剪函数trim
中文本中的空格。它几乎奏效了。我有一个问题,因为它也应该更改原始字符串,但它没有。问题出在哪里?请描述。我感谢你的帮助。谢谢:)代码:
#include <iostream>
#include <string.h>
using namespace std;
char* trim(char *str) {
while(*str==' '){
*str++;
}
char *newstr = str;
return newstr;
}
int main(){
char str[] = " Witaj cpp", *newstr;
cout << "start" << str << "end" << endl; // start Witaj cppend
newstr = trim(str);
cout << "start" << str << "end" << endl; // startWitaj cppend
cout << "start" << newstr << "end" << endl; // startWitaj cppend
return 0;
}
它不应该更改原始字符串,即使是像*str=something;
这样的代码也不会出现。要修改原始字符串,可以这样写
char* trim(char *str) {
char* oldstr = str;
while(*str==' '){
str++;//*str++; // What's the point of that *
}
char *str2 = oldstr;
while(*str!=' '){
*(str2++) = *(str++);
}
*str2 = ' ';
return oldstr;
}
您当前的代码只是在搜索空格。
您需要将空格字符替换为非空格字符。这通常是通过将非空格字符复制到第一个重复空格来实现的。
给定:
+---+---+---+---+---+---+---+---+---+---+---+---+---+------+
| P | e | a | r | | | | | f | r | u | i | t | ' ' |
+---+---+---+---+---+---+---+---+---+---+---+---+---+------+
您希望结果字符串看起来像:
+---+---+---+---+---+---+---+---+---+---+---+---+---+------+
| P | e | a | r | | | | | f | r | u | i | t | ' ' |
+---+---+---+---+---+---+---+---+---+---+---+---+---+------+
|
+-----------+
|
V
+---+---+---+---+---+---+---+---+---+---+------+
| P | e | a | r | | f | r | u | i | t | ' ' |
+---+---+---+---+---+---+---+---+---+---+------+
您可以通过取消引用指针来赋值。
在while
循环之后,您有:
+---+---+---+---+---+---+---+---+---+---+---+---+---+------+
| P | e | a | r | | | | | f | r | u | i | t | ' ' |
+---+---+---+---+---+---+---+---+---+---+---+---+---+------+
^
|
str --------------+
因此,您需要另一个跳过相邻空格的指针:
+---+---+---+---+---+---+---+---+---+---+---+---+---+------+
| P | e | a | r | | | | | f | r | u | i | t | ' ' |
+---+---+---+---+---+---+---+---+---+---+---+---+---+------+
^ ^
| |
++str ----------------+ |
|
non_space ------------------------+
递增目标指针src
,然后复制,直到找到字符串末尾或空格字符:
++str; // Skip past the first space.
*str++ = *non_space;
如果使用C++std::string
类型,则可以使用find_first_not_of
方法跳过空白。
std::string
还具有用于从字符串中移除字符的方法;并且CCD_ 8将根据需要移动字符。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错