开发者

Removal of special character in string in C++

开发者 https://www.devze.com 2023-01-30 21:19 出处:网络
I have the followoing string 开发者_StackOverflowmyStr = \"myname-abc\"; string myStr1 = strstr(myStr.c_str(), \"-\");

I have the followoing

string 开发者_StackOverflowmyStr = "myname-abc";

string myStr1 = strstr(myStr.c_str(), "-");

now in myStr1 i have -abc. But i don't want "-" infront of it i want to have "abc" how do i do that using string data type.

Thanks for help.


Not sure if I'm following, but you want to erase the first element?

str.erase(0, 1); // erases 1 element starting from position 0

Also, if you just want to erase everything up to -:

str.erase(0, str.find('-') + 1); 

If the data you are feeding the program isn't guaranteed to have a - somewhere, you should check the return value of str.find('-') for string::npos, the return value when no occurence is found.


string myStr1 = strstr(mStr.c_str(), "-") + 1;

or if you want to avoid converting to C style strings:

string myStr1(m_Str, m_Str.find('-') + 1);


size_t pos = myStr.find('-');
if (pos != std::string::npos)
{
    myStr1 = myStr.substr(pos + 1);
}


This program outputs

abc abc

int main()
{
    string myStr = "myname-abc";
    string myStr1 = strstr(myStr.c_str(), "abc");

    int index = 0;
    while(myStr[index++] != '-'){}
    string myStr2 = myStr.substr(index);

    cout << myStr1 << " " << myStr2 << endl;

    return 0;
}


std::string myStr("myname-abc");
std::string myStr1(++std::find(myStr.begin(), myStr.end(), '-'),
                   myStr.end());


If I understand what you are asking for, it's to remove instance of "-" from the string? If so, the following will also work..

string foo("-abc");
string::size_type fm = foo.find('-');
while (fm != string::npos)
{
  foo.erase(foo.begin() + fm);
  fm = foo.find('-', fm); // find the next instance of "-"
}


Removal of special character in string in C++

 #include<iostream.h>
 #include<conio.h>
 void main()
 {
 clrscr();
 char a[30];
 cout<<"enter any string ";
 cin.get(a,30);
 char b[30];
 for(int i=0;a[i]!='\0';i++)
 {
 if(a[i]!='!' && a[i]!='#'&& a[i]!='@' && a[i]!='$' && a[i]!='%' && a[i]!='^' && a[i]!='&'    && a[i]!='*' && a[i]!='?')
 {
 b[i]=a[i];
 cout<<b[i];
 } }
 getch();
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号