473,854 Members | 1,527 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do I take apart a string and get individual characters/words?

I used to program text RPG's in C back in high school, but I was very crude
at it and only learned what I needed to get the job done. I am now about to
graduate college with a degree in English and have had an interest in the
structure of language. In order to begin with my little program, I need to
be able to take a string like "The dog jumped." and be able to take the
first word from the sentence and assign it to a string, such as word1, then
skip the blank space and assign dog to the string word2 and then skip once
again and assign jumped to the string word3. I would give you some code I
was working with to try to do this, but I would rather save your stomachs
from hurting too much.... the laughter would be too much to bear =) But I
have attempted it on my own, and just need a little jump in the right
direction, if not just an all out solution. I appreciate any help you can
provide.
Jul 22 '05 #1
5 3140
For that, I would look up how to use stringstream.

Jul 22 '05 #2
So you want to tokenize the string.
One quick approach, however, is to use sstream:

#include <sstream>
#include <string>
#include <iostream>

int main()
{
std::istringstr eam s;
std::string w1, w2;

s.str("A b c");
s >> w1 >> w2;
std::cout << "word1 = "<< w1 << "\nword2 = " << w2 << "\n";
}
To really tokenize a C++ string, you'll need to write your own
function, however.

to get at the individual characters, you can use the subscript
operator, i.e.

string s = "_lah";
s[0] = 'b';
changes s to "blah"

So another possibility is to read the string and build a list of
words...

string stringVar = "blah blah blah";
vector <string> words;

for(pos = last = 0; pos < stringVar.lengt h(); pos++) {
if (stringVar[pos] == ' ') {
words.pushBack( stringVar.subst r(last, pos-lst));
last = pos+1;
}
}

Jul 22 '05 #3
derrick wrote:
I used to program text RPG's in C back in high school, but I was very crude
at it and only learned what I needed to get the job done. I am now about to
graduate college with a degree in English and have had an interest in the
structure of language. In order to begin with my little program, I need to
be able to take a string like "The dog jumped." and be able to take the
first word from the sentence and assign it to a string, such as word1, then
skip the blank space and assign dog to the string word2 and then skip once
again and assign jumped to the string word3. I would give you some code I
was working with to try to do this, but I would rather save your stomachs
from hurting too much.... the laughter would be too much to bear =) But I
have attempted it on my own, and just need a little jump in the right
direction, if not just an all out solution. I appreciate any help you can
provide.


I'd be tempted to say "buy a book". If you talk about such variables
(you seem not to know about arrays) and if you don't even know how to
parse a string, then I suggest you try to learn the language with simple
programs first.

Here's something to get you started with your problem.

# include <string>
# include <iostream>

int main()
{
std::string s = "The dog jumped.";

std::string::si ze_type start=0, end=0;

start = s.find_first_no t_of(" ");

if ( start == std::string::np os )
{
std::cout << "not found";
return 0;
}

end = s.find_first_of (" ", start);

if ( end == std::string::np os )
{
std::cout << "not found";
return 0;
}

std::cout << "first word: " << s.substr(start, end - start);
}

Look up std::string's member functions and std::vector for a collection
(such as for putting the individual words).
Jonathan
Jul 22 '05 #4

"derrick" <ra**********@y ahoo.com> wrote in message
news:Q5******** *******@newssvr 30.news.prodigy .com...
I used to program text RPG's in C back in high school, but I was very crude at it and only learned what I needed to get the job done. I am now about to graduate college with a degree in English and have had an interest in the
structure of language. In order to begin with my little program, I need to
be able to take a string like "The dog jumped." and be able to take the
first word from the sentence and assign it to a string, such as word1, then skip the blank space and assign dog to the string word2 and then skip once
again and assign jumped to the string word3. I would give you some code I
was working with to try to do this, but I would rather save your stomachs
from hurting too much.... the laughter would be too much to bear =) But I
have attempted it on my own, and just need a little jump in the right
direction, if not just an all out solution. I appreciate any help you can
provide.


#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>

int main()
{
std::string s("The dog jumped over the cat");
std::vector<std ::string> words;

std::istringstr eam iss(s);
std::copy(std:: istream_iterato r<std::string>( iss),
std::istream_it erator<std::str ing>(),
std::back_inser ter(words));

std::cout << "string: " << s << "\n\n"
<< "words:\n";

std::copy(words .begin(), words.end(),
std::ostream_it erator<std::str ing>(std::cout, ", "));

std::cout << "\n\n";

std::string word(words[2]);
std::cout << "Third word: " << word << "\n\n";

std::vector<cha r> w(words[2].begin(), words[2].end());

std::copy(std:: istream_iterato r<char>(iss),
std::istream_it erator<char>(),
std::back_inser ter(w));

std::cout << "Characters of \"" << word << "\"\n";

std::copy(w.beg in(), w.end(),
std::ostream_it erator<char>(st d::cout, ", "));

std::cout.put(' \n');
return 0;
}

-Mike
Jul 22 '05 #5
You have all been very helpful, except perhaps the first responder... I
appreciate all the help you have provided =) and my program is well on its
way since I last spoke to you all.
Jul 22 '05 #6

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

Similar topics

1
3378
by: Erinys | last post by:
Hi, I need to access the individual bytes in a string in my javascript function. If the characters in the string were all ascii characters then there would not be a problem, however in my case the string may contain ISO-2022-JP or UTF8 characters, so these characters may be larger than 1 byte each. Is there a way to extract the individual bytes, or convert a string to an array of bytes in javascript?
12
1857
by: Hp | last post by:
Hi All, Thanks a lot for all your replies. My requirement is as follows: I need to read a text file, eliminate certain special characters(like ! , - = + ), and then convert it to lower case and then remove certain stopwords(like and, a, an, by, the etc) which is there in another txt file. Then, i need to run it thru a stemmer(a program which converts words like running to run, ie, converts them to roots words).
4
12684
by: J | last post by:
anybody know a vb.net command to populate an array with each word in a string? for example " hi how are you" array(0) = hi array(1) = how array(2) = are array(3) = you i know i could loop though and search for spaces and build it that way...but a built in command would be great.
7
11626
by: JustSomeGuy | last post by:
I need to make a class called uid. A UID is a unique identifier. It looks like... 1.2.3.345.1.2.4.566 This uid get transmitted over a network as 8 bit binary data. If the length of the UID is odd, an extra padding null \0 is added to the end. This is what I've written but I'm not sure if I've garanteed to have the c_str() method return a buffer that is null padded.
24
4871
by: garyusenet | last post by:
I'm working on a data file and can't find any common delimmiters in the file to indicate the end of one row of data and the start of the next. Rows are not on individual lines but run accross multiple lines. It would appear though that every distinct set of data starts with a 'code' that is always the 25 characters long. The text is variable however. Assuming i've read the contents of the file into the string myfile, how do i split my...
7
2701
by: Leon | last post by:
Hi, I'm creating a python script that can take a string and print it to the screen as a simple multi-columned block of mono-spaced, unhyphenated text based on a specified character width and line hight for a column. For example, if i fed the script an an essay, it would format the text like a newspaper on the screen. Text processing is very new to me, any ideas on how I could achieve a multi-columned text formatter. Are there any...
1
3067
by: kellysgirl | last post by:
Now what you are going to see posted here is both the set of instructions I was given..and the code I have written. The instructions I was given are as follows In this case, you will create a Visual Basic 2005 solution that manipulates strings. It will parse a string containing a list of items within a text box and put the individual items into the list box. It will build the textbox string by putting the list box items together into a...
11
2910
by: Jacek Dziedzic | last post by:
Hi! I need a routine like: std::string nth_word(const std::string &s, unsigned int n) { // return n-th word from the string, n is 0-based // if 's' contains too few words, return "" // 'words' are any sequences of non-whitespace characters // leading, trailing and multiple whitespace characters // should be ignored.
6
2930
by: shapper | last post by:
Hello, I have a string and I need to get as many words possible counting from the beginning but without exceeding 120 characters. I can't break words and I the string shouldn't end with a comma, a dot, ... How can I do this? Thank You, Miguel
0
9901
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9751
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
10675
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9512
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
7912
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
7079
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
5740
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
5939
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4152
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.