473,795 Members | 2,892 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Stroustrup 5.9 exercise 12

problem: write a function that counts the number of occurences of a
pair of letters in a string. e.g the pair "ab" appears twice in
"xabaacbaxa bb".

i thought i could use "count()" from standard library but that works on
a container and "std::strin g" is not a container, its a class. even if
i put the "std::strin g" into a container then it will act as one elemnt
only e.g ["xabaaacbax abb"] and hence count will not work (i tried it).
so can you please give some idea in solving this problem?

Nov 9 '06 #1
8 2242
"arnuld" <ar*****@gmail. comwrites:
problem: write a function that counts the number of occurences of a
pair of letters in a string. e.g the pair "ab" appears twice in
"xabaacbaxa bb".

i thought i could use "count()" from standard library but that works on
a container and "std::strin g" is not a container, its a class. even if
i put the "std::strin g" into a container then it will act as one elemnt
only e.g ["xabaaacbax abb"] and hence count will not work (i tried it).
so can you please give some idea in solving this problem?
loop through each position in the string, taking this position + 1 as
a string, feed it into a map<string,intm ymap[ab]=i++.
Nov 9 '06 #2
arnuld wrote:
problem: write a function that counts the number of occurences of a
pair of letters in a string. e.g the pair "ab" appears twice in
"xabaacbaxa bb".

i thought i could use "count()" from standard library but that works on
a container and "std::strin g" is not a container, its a class. even if
i put the "std::strin g" into a container then it will act as one elemnt
only e.g ["xabaaacbax abb"] and hence count will not work (i tried it).
so can you please give some idea in solving this problem?
You can use the find method of the string object.

#include <iostream>
#include <string>

using namespace std;

int
main () {
// The string
string str = "xabaacbaxa bb";
// The null pos
string::size_ty pe pos = string::npos;
// Count matches
int count = 0;

// Set pos to next match
// Search for it again on next pos
// Until stop matching
while ((pos = str.find("ab", pos+1)) != string::npos) {
// Increment your counter while matches
count++;
}
cout << count << endl;
return 0;
}
You can also put everything inside a for loop:

for (pos = string::npos, count = 0;
(pos = haystack.find(n eedle, pos+1)) != string::npos;
count++)
;

--renato

--
Reclaim your digital rights, eliminate DRM, learn more at
http://www.defectivebydesign.org/what_is_drm
Nov 9 '06 #3
Renato Golin wrote:
You can use the find method of the string object.

#include <iostream>
#include <string>

using namespace std;

int
main () {
// The string
string str = "xabaacbaxa bb";
// The null pos
string::size_ty pe pos = string::npos;
// Count matches
int count = 0;

// Set pos to next match
// Search for it again on next pos
// Until stop matching
while ((pos = str.find("ab", pos+1)) != string::npos) {
// Increment your counter while matches
count++;
}
cout << count << endl;
return 0;
}
hey, it works, thanks :-) but i did not understand what "string::np os"
does.
>
You can also put everything inside a for loop:

for (pos = string::npos, count = 0;
(pos = haystack.find(n eedle, pos+1)) != string::npos;
count++)
;
what exactly the "haystack" is ?

Nov 9 '06 #4
arnuld wrote:
hey, it works, thanks :-) but i did not understand what "string::np os"
does.
npos is the null-position or no-position and it's a value defined by the
string implementation as "no position within this string". Each
implementation can create whatever number it wants to (negative,
MAX_INT, etc) so, to do a portable code you should never compare it to
the number you have now as "end-of-string" but to npos.

As zero is the first position it cannot be used to check if the find is
successful or not such as in:

if (!string.find(" foo"))

or

if ((pos = string.find("fo o")) == 0)

In my implementation, string::npos is 4294967295 (or max unsigned int)
as it does not allow strings bigger than that (I suppose). You can check
yours by simply:

cout << string::npos << endl;

But you should never use that value to check if the position is valid or
not.

Note that you should set pos to npos at the beginning because, if
something fails with find you will not be locked in that loop.

what exactly the "haystack" is ?
Literally is horse's food (normally loads of them), but it's a common
term used in search algorithms because of the phrase "finding a needle
in a haystack".

In algorithms phraseology. 'haystack' is the text or collection of
things you have and 'needle' is what you want to find there.

cheers,
--renato

--
Reclaim your digital rights, eliminate DRM, learn more at
http://www.defectivebydesign.org/what_is_drm
Nov 9 '06 #5
arnuld <ar*****@gmail. comwrote:
i thought i could use "count()" from standard library but that works on
a container and "std::strin g" is not a container, its a class.
Actually, std::string is a container of chars, but with a different
interface than the standard "containers ".

std::string is actually a typedef of std::basic_stri ng<char>.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Nov 9 '06 #6

Renato Golin wrote in message ...
>
In my implementation, string::npos is 4294967295 (or max unsigned int)
** as it does not allow strings bigger than that (I suppose)**. You can
check
>yours by simply:

cout << string::npos << endl;
std::string Aname( "hello" );
std::cout<<" string::npos ="<< std::string::np os << std::endl;
std::cout<<" string Aname.npos ="<< Aname.npos << std::endl;
std::cout<<" string Aname.max_size( ) ="<< Aname.max_size( ) << std::endl;
/* --- output --- (win32, MinGW(GCC)) YMMV
string::npos =4294967295
string Aname.npos =4294967295
string Aname.max_size( ) =1073741820 <<--------
*/

--
Bob R
POVrookie
Nov 9 '06 #7
BobR wrote:
string Aname.npos =4294967295
string Aname.max_size( ) =1073741820 <<--------
Good point bob,

I wonder why they limit to 1G instead of 4G-1...

--renato

--
Reclaim your digital rights, eliminate DRM, learn more at
http://www.defectivebydesign.org/what_is_drm
Nov 10 '06 #8

Renato Golin wrote in message
<45************ *********@newsr ead.sanger.ac.u k>...
>BobR wrote:
> string Aname.npos =4294967295
string Aname.max_size( ) =1073741820 <<--------

Good point bob,

I wonder why they limit to 1G instead of 4G-1...
renato
My rule is: when the string gets to be 999meg, I switch to vector<stringto
break it up a little. <G>

When is the last time you really needed a string that big?

On an old 40 column machine, using an old 66 lines per page printer, that's
nearly 380,000 pages! PER string!!<GThat' s a lot of trees!! So, by limiting
it to 1G, they were doing their part for conservation.
{ I gotta quit watching those old 'Three Stooges' movies! Nyuck nyuck nyuck.}

--
Bob R
POVrookie
Nov 11 '06 #9

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

Similar topics

26
3156
by: Oplec | last post by:
Hi, I am learning standard C++ as a hobby. The C++ Programming Language : Special Edition has been the principal source for my information. I read the entirety of the book and concluded that I had done myself a disservice by having not attempted and completed the exercises. I intend to rectify that. My current routine is to read a chapter and then attempt every exercise problem, and I find that this process is leading to a greater...
7
2351
by: arnuld | last post by:
problem: define functions F(char), g(char&) & h(const char&). call them with arguments 'a', 49, 3300, c, uc & sc where c is a char, uc is unsigned char & sc is signed char. whihc calls are legal? which calls cause the compiler to to introduce a temporary variable? solution: this is the code ----------------------------------------------------------- #include <iostream> void f(char) {};
0
1755
by: arnuld | last post by:
Stroustrup has a table in section 4.9 of declarations and definitions. he asks to write a similar table but in opposite sense: char ch; // declaration with definition he asks to do the opposite as an exercise which is writing it as a "declaration without definition". please check whether i am right or wrong:
0
1759
by: arnuld | last post by:
this programme runs without any trouble. it took 45 minutes of typing. i posted it here so that people can save their precious time: // Stroustrup special edition // chapter 4 exercise 2 // printing the sizes of different types
2
5339
by: arnuld | last post by:
MAX and MIN values of CHAR could not be displayed. Why ? BTW, any advice on improvement ? (please remember i have covered chapter 4 only) ------------- PROGRAMME -------------- /* Stroustrup 3e, section 4.11, exercise 5 STATEMENT:
16
2375
by: arnuld | last post by:
i did what i could do at Best to solve this exercise and this i what i have come up with: ----------- PROGRAMME -------------- /* Stroustrup 5.9, exercise 3 STATEMENT: Use typedef to define the types: unsigned char
11
1844
by: arnuld | last post by:
/* Stroustrup: 5.9 exercise 7 STATEMENTS: Define a table of the name sof months o fyear and the number of days in each month. write out that table. Do this twice: 1.) using ar array of char for names of months and an array of numbers for number of days. 2.) using an array of structures. each structure holds the name of the
6
3044
by: arnuld | last post by:
this one was much easier and works fine. as usual, i put code here for any further comments/views/advice: --------- PROGRAMME ------------ /* Stroustrup: 5.9 exercise 7 STATEMENTS: Define a table of the name sof months o fyear and the number of days in each month. write out that table. Do this twice:
14
2481
by: arnuld | last post by:
there is no "compile-time error". after i enter input and hit ENTER i get a run-time error. here is the code: ---------- PROGRAMME -------------- /* Stroustrup, 5.9, exercise 11 STATEMENT: Read a sequence of words from the input. use "quit" as the word
27
2457
by: arnuld | last post by:
it works fine without any trouble. i want to have advice on improving the code from any angle like readability, maintenance etc: ---------- PROGRAMME ------------ /* Stroustrup, 5.9, exercise 11 STATEMENT: Read a sequence of words from the input. use "quit" as the word to terminate the input. Print the words in the order they were entered. don't print a word twice.modify the programme to sort the
0
9519
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
10438
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...
0
10001
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
9042
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
7540
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
6780
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();...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.