C++从字符末尾删除值

C++ remove value from end of char

本文关键字:删除 字符 C++      更新时间:2023-10-16

这只是从一个名为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;
}