Reputation: 272
I'm trying to delete first 'w' and last 'w' from a string. I deleted the first 'w', but couldn't delete the last one, and here is my code:
char str1[80], *pstr1, *pstr2;
cout << "Enter a String:\n";
gets_s(str1);
pstr1 = str1;
pstr2 = new char[strlen(str1)];
int n = strlen(str1) + 1, k = 0, i = 0;
bool s = true;
while (k < n+1)
{
if (strncmp((pstr1 + k), "w", 1) != 0)
{
*(pstr2 + i) = *(pstr1 + k);
i++;
k++;
}
else if(s == true)
{
k++;
s = false;
}
else
{
*(pstr2 + i) = *(pstr1 + k);
i++;
k++;
}
}
Upvotes: 1
Views: 79
Reputation: 10393
Make your life easy and use std::string
with find_first_of
, find_last_of
and erase
.
#include <string>
void erase_first_of(std::string& s, char c)
{
auto pos = s.find_first_of(c);
if (pos != std::string::npos)
{
s.erase(pos, 1);
}
}
void erase_last_of(std::string& s, char c)
{
auto pos = s.find_last_of(c);
if (pos != std::string::npos)
{
s.erase(pos, 1);
}
}
#include <iostream>
int main()
{
std::string s = "hellow, worldw\n";
erase_first_of(s, 'w');
erase_last_of(s, 'w');
std::cout << s;
}
Upvotes: 3