473,757 Members | 9,145 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is this code to find an int in a string okay ?

Hi Guys,

Is there any better way than below to find an int in a string (e.g.
"30" in "KFStat30A" )

// --------------------------------------------------------------
#include <iostream>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
vector<string strs ;
strs.push_back( "KFStat30A" );
strs.push_back( "KFStat2A") ;
strs.push_back( "555555");
strs.push_back( "KKKKKK");
strs.push_back( "KKKK555");

std::string str;

for (int i=0; i<strs.size(); i++)
{
str = "";

int beg = strs[i].find_first_of( "0123456789 ");

if (beg != string::npos)
{
int end = strs[i].find_first_not _of("0123456789 ", beg);
str.assign(strs[i], beg, end-beg);
}

cout << strs[i] << " " << str << "\n";
}
return 0;
}

// --------------------------------------------------------------

Thanks
-- Diwa
Dec 6 '07 #1
8 2782
"Diwa" <sh***********@ gmail.comwrote in message
news:85******** *************** ***********@j44 g2000hsj.google groups.com...
Hi Guys,

Is there any better way than below to find an int in a string (e.g.
"30" in "KFStat30A" )

// --------------------------------------------------------------
#include <iostream>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
vector<string strs ;
strs.push_back( "KFStat30A" );
strs.push_back( "KFStat2A") ;
strs.push_back( "555555");
strs.push_back( "KKKKKK");
strs.push_back( "KKKK555");

std::string str;

for (int i=0; i<strs.size(); i++)
{
str = "";

int beg = strs[i].find_first_of( "0123456789 ");

if (beg != string::npos)
{
int end = strs[i].find_first_not _of("0123456789 ", beg);
str.assign(strs[i], beg, end-beg);
}

cout << strs[i] << " " << str << "\n";
}
return 0;
}
This code looks okay. Although I wonder what you would want with a string
such as
"KFStat30A0 2". Your code could be described as finding the first continuous
number in a string. I really don't think you can simply if too much though
from what you already have, other than making it a function returning a
std::string.
Dec 6 '07 #2
Jim Langston wrote:
"Diwa" <sh***********@ gmail.comwrote in message
news:85******** *************** ***********@j44 g2000hsj.google groups.com...
>Hi Guys,

Is there any better way than below to find an int in a string (e.g.
"30" in "KFStat30A" )

// --------------------------------------------------------------
#include <iostream>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
vector<string strs ;
strs.push_back( "KFStat30A" );
strs.push_back( "KFStat2A") ;
strs.push_back( "555555");
strs.push_back( "KKKKKK");
strs.push_back( "KKKK555");

std::string str;

for (int i=0; i<strs.size(); i++)
{
str = "";

int beg = strs[i].find_first_of( "0123456789 ");

if (beg != string::npos)
{
int end = strs[i].find_first_not _of("0123456789 ", beg);
str.assign(strs[i], beg, end-beg);
}

cout << strs[i] << " " << str << "\n";
}
return 0;
}

This code looks okay. Although I wonder what you would want with a
string such as
"KFStat30A0 2". Your code could be described as finding the first
continuous number in a string. I really don't think you can simply
if too much though from what you already have, other than making it a
function returning a std::string.
I would probably add the ability to extract the substring as a number
in a given base. E.g., "KFStat30A0 2" in base 10 would yield "30" and
in base 16 would yield "F"... :-) Or make it smarter and able to
recognize the 'x' or 'X' after the leading 0...

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Dec 6 '07 #3
In article
<85************ *************** *******@j44g200 0hsj.googlegrou ps.com>,
Diwa <sh***********@ gmail.comwrote:
Hi Guys,

Is there any better way than below to find an int in a string (e.g.
"30" in "KFStat30A" )

// --------------------------------------------------------------
#include <iostream>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
vector<string strs ;
strs.push_back( "KFStat30A" );
strs.push_back( "KFStat2A") ;
strs.push_back( "555555");
strs.push_back( "KKKKKK");
strs.push_back( "KKKK555");

std::string str;

for (int i=0; i<strs.size(); i++)
{
str = "";

int beg = strs[i].find_first_of( "0123456789 ");

if (beg != string::npos)
{
int end = strs[i].find_first_not _of("0123456789 ", beg);
str.assign(strs[i], beg, end-beg);
}

cout << strs[i] << " " << str << "\n";
}
return 0;
}

// --------------------------------------------------------------

Thanks
What you have is fine, just wrap it into a function and it will look
like this:

string get_int( const string& s )
{
string result;
string::size_ty pe front = s.find_first_of ( "0123456789 " );
if ( front != string::npos )
{
string::size_ty pe back =
s.find_first_no t_of( "0123456789 ", front );
result.assign( s, front, back - front );
}
return result;
}

.... or you can get creative:

bool is_digit( char c )
{
return isdigit( c );
}

string get_int( const string& s )
{
string::const_i terator front = find_if( s.begin(), s.end(),
&is_digit );
string::const_i terator back = find_if( front, s.end(),
compose1( logical_not<boo l>(), ptr_fun( &is_digit ) ) );
return string( front, back );
}

(note: compose1 is part of STL, not part of the standard.)

Once you have the above function, you can operate on your array with
transform.

int main()
{
vector<string strs ;
strs.push_back( "KFStat30A" );
strs.push_back( "KFStat2A") ;
strs.push_back( "555555");
strs.push_back( "KKKKKK");
strs.push_back( "KKKK555");

vector<stringin ts;

transform( strs.begin(), strs.end(),
back_inserter( ints ), &get_int );

for ( int i = 0; i < strs.size(); ++i )
cout << strs[i] << ' ' << ints[i] << '\n';
}
Dec 7 '07 #4
On Dec 6, 3:51 pm, Diwa <shettydiwa...@ gmail.comwrote:
Is there any better way than below to find an int in a string
(e.g. "30" in "KFStat30A" )
boost::regex.

If for some reason, you can't use Boost (most people probably
can't), then beg, borrow or steal some other regular expression
class. You don't want to do anything with text without one.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Dec 7 '07 #5
On Dec 6, 5:31 pm, "Jim Langston" <tazmas...@rock etmail.comwrote :
"Diwa" <shettydiwa...@ gmail.comwrote in message

news:85******** *************** ***********@j44 g2000hsj.google groups.com...
Hi Guys,
Is there any better way than below to find an int in a string (e.g.
"30" in "KFStat30A" )
// --------------------------------------------------------------
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
vector<string strs ;
strs.push_back( "KFStat30A" );
strs.push_back( "KFStat2A") ;
strs.push_back( "555555");
strs.push_back( "KKKKKK");
strs.push_back( "KKKK555");
std::string str;
for (int i=0; i<strs.size(); i++)
{
str = "";
int beg = strs[i].find_first_of( "0123456789 ");
if (beg != string::npos)
{
int end = strs[i].find_first_not _of("0123456789 ", beg);
str.assign(strs[i], beg, end-beg);
}
cout << strs[i] << " " << str << "\n";
}
return 0;
}

This code looks okay. Although I wonder what you would want with a string
such as "KFStat30A0 2".
- Show quoted text -
The strings come from a database. The "30" in that string represents
the 30 yr treasury bond. Only the first two strings (KFStat30A and
KFStat2A) were valid ones. I had put the other three strings just for
testing purpose.
Dec 7 '07 #6
On Dec 7, 7:26 am, "Daniel T." <danie...@earth link.netwrote:
In article
<85ec7280-977f-4651-a3f4-2199b4150...@j4 4g2000hsj.googl egroups.com>,

Diwa <shettydiwa...@ gmail.comwrote:
Hi Guys,
Is there any better way than below to find an int in a string (e.g.
"30" in "KFStat30A" )
// --------------------------------------------------------------
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
vector<string strs ;
strs.push_back( "KFStat30A" );
strs.push_back( "KFStat2A") ;
strs.push_back( "555555");
strs.push_back( "KKKKKK");
strs.push_back( "KKKK555");
std::string str;
for (int i=0; i<strs.size(); i++)
{
str = "";
int beg = strs[i].find_first_of( "0123456789 ");
if (beg != string::npos)
{
int end = strs[i].find_first_not _of("0123456789 ", beg);
str.assign(strs[i], beg, end-beg);
}
cout << strs[i] << " " << str << "\n";
}
return 0;
}
// --------------------------------------------------------------
Thanks

What you have is fine, just wrap it into a function and it will look
like this:

string get_int( const string& s )
{
string result;
string::size_ty pe front = s.find_first_of ( "0123456789 " );
if ( front != string::npos )
{
string::size_ty pe back =
s.find_first_no t_of( "0123456789 ", front );
result.assign( s, front, back - front );
}
return result;

}

... or you can get creative:

bool is_digit( char c )
{
return isdigit( c );

}

string get_int( const string& s )
{
string::const_i terator front = find_if( s.begin(), s.end(),
&is_digit );
string::const_i terator back = find_if( front, s.end(),
compose1( logical_not<boo l>(), ptr_fun( &is_digit ) ) );
return string( front, back );

}
What would the above func return if the string (e.g. KFStat30A55BB)
contains 2 ints instead of one ?
Dec 7 '07 #7
On Dec 7, 11:18 am, James Kanze <james.ka...@gm ail.comwrote:
On Dec 6, 3:51 pm, Diwa <shettydiwa...@ gmail.comwrote:
Is there any better way than below to find an int in a string
(e.g. "30" in "KFStat30A" )

boost::regex.

If for some reason, you can't use Boost (most people probably
can't), then beg, borrow or steal some other regular expression
class. You don't want to do anything with text without one.
Thanks. That was what I originally wanted to use since we are using
boost anyway in our code. But later we decided against it since we do
not require any regex parsing except for this one. Boost regex would
have been an overkill especially considering the fact that boost regex
requires its library to be linked to the app. (If I am not wrong)
Dec 7 '07 #8
Diwa <sh***********@ gmail.comwrote:
Daniel T. wrote:
string get_int( const string& s )
{
string result;
string::size_ty pe front = s.find_first_of ( "0123456789 " );
if ( front != string::npos )
{
string::size_ty pe back =
s.find_first_no t_of( "0123456789 ", front );
result.assign( s, front, back - front );
}
return result;

}

... or you can get creative:

bool is_digit( char c )
{
return isdigit( c );

}

string get_int( const string& s )
{
string::const_i terator front = find_if( s.begin(), s.end(),
&is_digit );
string::const_i terator back = find_if( front, s.end(),
compose1( logical_not<boo l>(), ptr_fun( &is_digit ) ) );
return string( front, back );

}

What would the above func return if the string (e.g. KFStat30A55BB)
contains 2 ints instead of one ?
The first int. Both "get_int" functions above work in the same way. They
scan the string looking for the first digit, then scan from there
looking for the first non-digit, then output a string containing all the
data between the two positions found.
Dec 7 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
2010
by: Bshealey786 | last post by:
Okay im doing my final project for my first computer science class(its my major, so it will be my first of many), but anyway im a beginner so im not to great with C++ yet. Anyway this is the error msg that im getting: "Error executing cl.exe" this is the code that I have, but I know whats causing it, ill just show you the whole thing first though //file: Quadratic
143
8089
by: suri | last post by:
Hello I downloaded glibc and tried looking for the code that implements the sine function i couldnt find the file. i went to the math directory and found math.h.. i guess that needs to be included for the sine function. but which .c file implements the sine/cosine and other trig fns thanks
8
1403
by: Sandy | last post by:
Hello - This code was snagged by me from the Internet and altered. Its purpose is to check for swear words. It works the way it currently is, but I need it to be more generic -- i.e., I don't want it to refer to TextBox1 or Label1 directly; I want to be able to plug in the name of any textbox into CheckString(TextBox1.Text), instead of just a specific textbox. Public Sub CheckString(inputstring as string) Dim alWordList as New...
19
9592
by: ashmangat | last post by:
Hi! now on the chapter "string-class" My assignment is below Word Counter: Write a function that accepts a pointer to a C-String as an argument and returns the number of words contained in the string. For instance, if the string argument is "Four score and seven years ago" the function should return the number 6. Demonstrate the function in a program that asks the user to input a string and then passes it to the function. The number of...
6
2346
by: TPJ | last post by:
Help me please, because I really don't get it. I think it's some stupid mistake I make, but I just can't find it. I have been thinking about it for three days so far and I still haven't found any solution. My code can be downloaded from here: http://www.tprimke.net/konto/PyObject-problem.tar.bz2. There are some scripts for GNU/Linux system (bash to be precise). All you need to know is that there are four classes. (Of course, you may...
15
4639
by: Cheryl Langdon | last post by:
Hello everyone, This is my first attempt at getting help in this manner. Please forgive me if this is an inappropriate request. I suddenly find myself in urgent need of instruction on how to communicate with a MySQL database table on a web server, from inside of my company's Access-VBA application. I know VBA pretty well but have never before needed to do this HTTP/XML/MySQL type functions.
0
964
by: Max | last post by:
If you don't want to read the drivel in my main message body here is the question at the end. How do you find a string in a column and make the BindingNavigator Navigate to the correct row?? Thanks, --max I added a table (logouts) to a form from the datasource. This added the LogoutsBindingNavigator, LogoutsBindingSource, and LogoutTableAdapter. This is all find and dandy, now I want to find a record without scrolling to the record....
7
1368
by: =?Utf-8?B?Q2hyaXM=?= | last post by:
Hi, How can I implement regex to find complete or partial words or a group of words. Similar to the "Find" in MS Word. I need to scan text files eg look for "test" or "this is a test" or "this is a te" Thanks
1
8104
by: tk121 | last post by:
Hey all - I have some unmanaged code that I'm calling into with C# .NET 2.0, and everything works flawlessly in the debugger, but as soon as I run the application as a standalone executable it unexpectedly quits without throwing any exceptions. Even if I start the executable in the debugger it works okay. To see the failure, I need to start the application and then attach the debugger to the process. The function call will work okay twice...
0
9298
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10072
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9885
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9737
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8737
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7286
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6562
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3829
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3399
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.