hi, i want to know in c++ how can we extract things we want from a string. for example, if a user input 3434dfgrs3345, the output will be 34343345 instead of the char. :)
Need some answers
Started by debug, Aug 24 2007 04:37 AM
4 replies to this topic
#1
Posted 24 August 2007 - 04:37 AM
|
|
|
#2
Posted 24 August 2007 - 05:01 AM
Look at this:
#include <iostream>
#include <string>
std::string ExtractNumbers(std::string Source)
{
std::string Destination = "";
for(int i = 0; i < Source.length(); i++)
if(static_cast<int>(Source.at(i)) > 47 &&
static_cast<int>(Source.at(i)) < 58)
Destination += Source.at(i);
return Destination;
}
int main()
{
std::string MyStringWithChars = "3434dfgrs3345";
std::string MyStringWithoutChars = ExtractNumbers(MyStringWithChars);
std::cout << MyStringWithChars << std::endl;
std::cout << MyStringWithoutChars << std::endl;
return 0;
}
This could probably be done with a stringstream as well.
#3
Posted 27 August 2007 - 05:23 PM
Look into the Regex library set. It can be used to extract anything from anything using simple calls. However, using functions like the one void listed above works perfectly for what you (seem) to want.
#4
Posted 30 August 2007 - 05:34 PM
thank for the reply. got another question to ask. how to change the below code into a function?
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char myAddress[100] = {0};
int i;
cout <<"Enter the address:";
cin.getline(myAddress, 40);
for(i=0; i<100; i++)
{
if(static_cast<int>(myAddress[i])>=48 && static_cast<int>(myAddress[i])<=57)
{
cout<< myAddress[i];
}
}
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char myAddress[100] = {0};
int i;
cout <<"Enter the address:";
cin.getline(myAddress, 40);
for(i=0; i<100; i++)
{
if(static_cast<int>(myAddress[i])>=48 && static_cast<int>(myAddress[i])<=57)
{
cout<< myAddress[i];
}
}
return 0;
}
#5
Posted 30 August 2007 - 08:59 PM
I don't know what of the code you want to be in a function.
I don't know if you have to use C-strings neither, because if you're using C++-strings, it would be easier for you.
I don't know if you have to use C-strings neither, because if you're using C++-strings, it would be easier for you.
#include <iostream>
#include <string>
int main()
{
std::string myAddress;
std::cout <<"Enter the address: ";
std::getline(std::cin, myAddress);
std::cout << "My address: " << myAddress << std::endl;
return 0;
}


Sign In
Create Account


Back to top









