C++从字符末尾删除值
C++ remove value from end of char
这只是从一个名为inputArray
的单词数组中获取每个 delims 值,并在每个循环之后转到下一个单词。
每个单词都称为sub
。
问题是一旦在末尾找到带有"s"的单词,我想删除"s"并使sub
= 新单词。
我当前的方法将 sub 变回一个名为stringTemp
的字符串,然后删除"s"并将其变回字符sub
。
char inputDelim[] = " ";
char* sub = strtok(InputArray, inputDelim);
while(sub)
{
//This sets up the ability to find if 's' is at the end of the word
int n = strlen(sub);
int v = n;
char *vw = &sub[0u];
v--;
/////////////////////
//The problem is here
/////////////////////
if(vw[v] == 's')
{
string stringTemp = string(sub);
stringTemp.erase(stringTemp.end() - 1);
sub = str.c_str();//This does not work. Can not convert const char* into char*
s = 1;
r = 1;
}
...lots more code...
sub = strtok(NULL, inputDelim);
}
sub 在代码中进一步用于不同的手段。
任何人都可以帮助使此方法起作用,或者向我展示另一种可以删除sub
字符末尾的"s"的方法?
我不应该为此苦苦挣扎,但可悲的是我是。
谢谢!
您指出的另一个问题:
//...
int v = n;
char *vw = &sub[0u];
v--;
/////////////////////
//The problem is here
/////////////////////
if(vw[v] == 's') // v points the the NULL char at the end of vw.
// should read:
if(vw[v - 1] == 's') // v points the the last char of string vw
主要问题是,一旦你开始在InputArray上使用strtok,你就不应该弄乱它。 strtok 几乎拥有字符串的内容,甚至修改它。 你试图写进sub
(它指向InputArray
内部(有效地破坏了strtok
的内部逻辑。
你可以通过从get到使用std::string来拯救自己这个刺激性的错误。 strtok(( 远非完美......
此代码适用于 C++03。C++11 引入了 std::find_if_not,并弃用了 std::not1。
#include <string>
#include <iostream>
#include <algorithm>
#include <cctype>
using namespace std;
bool is_space(char c)
{
return isspace(static_cast<unsigned char>(c)) != 0;
}
int main()
{
string no_s;
//...
string phrase = "hello world and its riches";
string::iterator p1;
string::iterator p2 = phrase.begin();
while ((p1 = find_if(p2, phrase.end(), not1(ptr_fun(is_space)))) != phrase.end())
{
p2 = find_if(p1 + 1, phrase.end(), is_space);
string sub(p1, p2);
if (*sub.rbegin() == 's')
sub.resize(sub.length() - 1);
no_s += sub + " ";
}
if (no_s.length())
no_s.resize(no_s.length() - 1);
cout << no_s;
return 0;
}
相关文章:
- 正在从C++中的字符数组中删除字符
- 从字符串中删除字符
- 如果不是十六进制,则QT从qlineedit中删除字符
- 从长字符串中删除字符
- 从文件对象的当前位置删除字符
- C++ 删除字符**
- 从字符串中删除字符的第一个和最后一个实例
- 如何在C++中删除字符*数组
- 如何从C 中的字符串中删除字符
- 用“ strcpy”在2D数组中删除(字符)的一行(字符)时是否存在任何错误
- 删除字符并在字符串(C )的末端附加它们
- C++ 字符串,用于删除字符'b'并将字符'a'替换为两个'd'的构建函数
- 在字符串中的定界符之间删除字符
- 从 std::字符串中删除字符从 "(" 到 ")" 用擦除?
- 使用擦除和删除从字符串中删除字符
- C++ 如何删除字符中的双引号
- C++ 中的密码 |打印字符后删除字符
- C++在链表中插入和删除字符
- 字符串流的获取函数不删除字符
- 删除字符C++最后一次出现时字符数组的开头