pocketshotgun

C++ questions about strings

Recommended Posts

Hello!

 

So I have been learning c++ for a bit now and I have a few questions regarding string(s) and char(s)

I know how to get a string or char input but I am wondering how to separate a sentence into words without using multiple strings.

 

For example:

 

string example;

cin >> example;

 

If I input "Hello World" as the example string is there a way to tell the computer to separate the example string into two words, "Hello" and "World"?

 

I would think that this would be done by detecting spaces somehow but I am not quite sure how.

 

I am also wondering if there is a way to make the string ignore if the example string has uppercase and lowercase.

 

And one last thing which is not about strings, how would I make a float or int random, for example:

 

if(example == "hello")

{

     cout << randomInt;

}

 

I would really appreciate any help, THANKS!

Share this post


Link to post
Share on other sites

(edited)

C++ n00b here

 

To separate a string into two words you would have to find the length of the string you want to separate then find the space that separates them then separate them into two strings by using the .substr() method (well that is what I do)

 

for example:

#include <iostream>
using namespace std;
int main()
{
string name;
cout<<"enter two words: ";
getline(cin, name);
 
int length = name.length();
char space = name.find(" ");
string first = name.substr(0, space);
space = space + 1;
string last = name.substr(space, length);
cout<<"first: "<<first<<endl;
cout<<"second: "<<last;
 
int hold;
cin>>hold;
return 0;
}
 
output:
enter two words: two words
first: two
second: words
 
 
 

 

 

how would I make a float or int random
 

This is what I was taught:

 

#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
int main ()
{
      time_t seconds;
      time(&seconds);
      srand((unsigned int) seconds);
 
      int random = rand();
      
      cout<<random<<endl;
 
      //you can change the range of the random number
 
      random = rand()%10;  //the max number this can generate is 10
      
      cout<<random;
}
Edited by u53rn4m3

Share this post


Link to post
Share on other sites

If you're willing to learn a bit of new syntax, stringstream can do a lot of fancy-pantsy string manipulation. It works a lot like cin does.

#include <iostream>
#include <string>
#include <sstream>//stringstream is located here

using namespace std;

int main()
{
    string input;
    cout<<"Enter sentence: ";

    //Reads in user input, important to use getline instead of cin>> to read in the whole line
    //instead of only the first token/word
    getline(cin, input);

    //reads the input into a stringstream for fancy operations
    stringstream ss(input);

    string word;

    //getline(ss, word, ' ') reads each token (strings separated by the char delimiter, ' ')
    //and stores the result in 'word', returns false once the end of the string is reached
    for(int i = 1; getline(ss, word, ' '); i++)
        cout<< i << ": " << word <<endl;
}

Output:

Enter sentence: Hello world! May I take your order?
1: Hello
2: world!
3: May
4: I
5: take
6: your
7: order?

Interestingly enough, since a space is the default delimiter, getline(ss, word, ' ') could be replaced with ss>>word, but the first was used to show that any delimiter can be used.

 

I am also wondering if there is a way to make the string ignore if the example string has uppercase and lowercase.

Howso? What are you trying to do with it?

 

Feel free to ask any other questions you might have. I'm actually a convert from Java (I've been saved! Hallelujah! Praise the heavens!) so even though I don't know all the syntax I'd be more than happy to learn along with you.

Share this post


Link to post
Share on other sites

(edited)

If you're willing to learn a bit of new syntax, stringstream can do a lot of fancy-pantsy string manipulation. It works a lot like cin does.

#include <iostream>
#include <string>
#include <sstream>//stringstream is located here

using namespace std;

int main()
{
    string input;
    cout<<"Enter sentence: ";

    //Reads in user input, important to use getline instead of cin>> to read in the whole line
    //instead of only the first token/word
    getline(cin, input);

    //reads the input into a stringstream for fancy operations
    stringstream ss(input);

    string word;

    //getline(ss, word, ' ') reads each token (strings separated by the char delimiter, ' ')
    //and stores the result in 'word', returns false once the end of the string is reached
    for(int i = 1; getline(ss, word, ' '); i++)
        cout<< i << ": " << word <<endl;
}

Output:

Enter sentence: Hello world! May I take your order?
1: Hello
2: world!
3: May
4: I
5: take
6: your
7: order?

Interestingly enough, since a space is the default delimiter, getline(ss, word, ' ') could be replaced with ss>>word, but the first was used to show that any delimiter can be used.

 

Howso? What are you trying to do with it?

 

Feel free to ask any other questions you might have. I'm actually a convert from Java (I've been saved! Hallelujah! Praise the heavens!) so even though I don't know all the syntax I'd be more than happy to learn along with you.

(accidentaly quoted the whole post, sorry)

 

But actually yes, I do have another question, at this point I am quite new to C++ (I used to do js) but I am wondering how to find a keyword within a string (a substring I believe it's called) for example:

 

string word;

cout << "Input Sentence" << endl;

cin >> word;

 

but if I entered "hello world", how would I tell C++ to check if the keyword "hello" was there?

or if I entered "what is the time" to check for the keywords "what" and/or "time"

 

If you don't know that's ok, I just thought I'd ask here direcly because I had searched for a few hours and found nothing that was exactly as I needed.

 

Thanks!

Edited by pocketshotgun

Share this post


Link to post
Share on other sites

(edited)

This is both easy and complicated.

The easiest answer is this: to search a string, use string::find(string), like u53rn4m3 suggested. That will return a number, which is the index (or position in the string) of the search. If the string is not found, it will return -1.

#include <string>
#include <iostream>

using namespace std;

int main()
{
    cout << "Enter sentence: ";
    string s;
    getline(cin, s);
    int index = s.find("Hello"); // Searches s for the substring "Hello" and returns its location/index
    if(index >= 0) //NOT -1
        cout << "Found at index " << index << endl;
    else //returned -1
        cout << "Not found" << endl;
}

Output 1:

Enter sentence: Hello world!
Found at index 0

Output 2:

Enter sentence: He's a cranky doodle donkey guy
Not found

This solution may work for what you're trying to do, but for most basic purposes it is a little lack-luster.

Two reasons I can think of:

1) what happens when we want to find more than one instance of "hello"?

2) string::find is case-sensitive; if I had typed "hello world", "HEllo world" or any other variant, it wouldn't have found it.

 

As a solution to the first, string::find can also accept an index number to tell it where in the string to start looking. If we use the index from finding it once as a starting point, we can continue to search.

#include <string>
#include <iostream>

using namespace std;

int main()
{
    cout << "Enter sentence: ";
    string s;
    getline(cin, s);
    int last_found = 0, index;
    bool found = false;
    do
    {
        index = s.find("wood", last_found); //starts searching at index last_found
        if(index >= 0) // if wood was found
        {
            found = true;
            last_found = index + 1; //+1 to begin one char AFTER the last one found
            cout << "Found at index " << index << endl;
        }
    }while(index >= 0); //either it wasn't found or the end was reached
    if(!found)
        cout << "Not found";
}

Output:

Enter sentence: How much wood could a woodchuck chuck if a woodchuck could chuck wood?
Found at index 9
Found at index 22
Found at index 43
Found at index 65

As a solution for 2, well, we can do something incredibly inefficient (but fun and functional!). In order to ignore uppercase/lowercase we just internally turn the string we want to search into all upper/lowercase letters to match what we're searching for.

#include <string>
#include <iostream>

using namespace std;

int main()
{
    cout << "Enter sentence: ";
    string s, s_new;
    getline(cin, s);

    //reads the string, char by char, and adds uppercase chars to s_new
    for(int i = 0; i < s.length(); i++)
        s_new += toupper(s[i]);
    int index = s_new.find("PROBLEMFACTORY");
    if(index >= 0) //NOT -1
        cout << "Found at index " << index << endl;
    else //returned -1
        cout << "Not found" << endl;
}

Output 1:

Enter sentence: Some people, when they have a problem, think, "I know! I'll use Java!" Now they have a ProblemFactory.
Found at index 87

Output 2 (perhaps more conventional)

Enter sentence: Don't have a pRobLemFaCtORy!
Found at index 13

Boom. Man, I've having a lot of fun doing this.

 

Thanks!

You're welcome.

 

EDIT: For some reason some characters are getting erased on line 15 of that last one. I just don't know what went wrong. Just add the ')', ';' and '\n'.

EDIT EDIT: Aaaaaand now they're back. Err. Disregard.

Edited by Mort

Share this post


Link to post
Share on other sites

Python all da way m8...

 

(Actually I am starting to do C++ as well sooo...)

Share this post


Link to post
Share on other sites

Python all da way m8...

>>> from __future__ import braces

File "<stdin>", line 1

SyntaxError: not a chance

 

I would like to learn Python too. It's on my to-do list.

Share this post


Link to post
Share on other sites

>>> from __future__ import braces

File "<stdin>", line 1

SyntaxError: not a chance

 

I would like to learn Python too. It's on my to-do list.

Python's pretty damn easy in my opinion :D

Share this post


Link to post
Share on other sites

Python's pretty damn easy in my opinion :D

Python's hard. Lua's easier. C++ is too complex. C is the best. ASM is fun. I actually have programmed in AVR machine code. :toldya:

Share this post


Link to post
Share on other sites

Python's hard. Lua's easier. C++ is too complex. C is the best. ASM is fun. I actually have programmed in AVR machine code. :toldya:

I actually have programmed in AVR machine code. :toldya:

machine code

1392389701823.jpg

 

Sorry, couldn't help it.

Well if we're all going to be like that then TI-BASIC is best language

Or maybe LOLCODE or Whitespace

 

I have a friend who keeps trying to talk me into C# but I kinda blow him off because lol microsoft and I really am more comfortable with C++. I plan on learning Python to have the benefits of an interpreted language, although I always have been frightened by the lack of braces. No doubt I could get used to it. Perhaps I'm just too traditionalist to look into anything else for now.

Share this post


Link to post
Share on other sites

1392389701823.jpg

 

Sorry, couldn't help it.

What? Is programming in machine code somehow demented in the likes of TI-Basic? I find it fun to learn, not for practical pursuits, but for fun.

Share this post


Link to post
Share on other sites

What? Is programming in machine code somehow demented in the likes of TI-Basic? I find it fun to learn, not for practical pursuits, but for fun.

Nahh, I just wanted to use the machine code meme because I never have gotten to before XD

I think out would be fun to learn the more inner workings of machine code, and I absolutely refuse to die before I program something with punchcards.

And don't be hatin on TI-BASIC I've seen it perform miracles when you put enough faith (and blood/tears/animal sacrifice) into it

Share this post


Link to post
Share on other sites

Nahh, I just wanted to use the machine code meme because I never have gotten to before XD

I think out would be fun to learn the more inner workings of machine code, and I absolutely refuse to die before I program something with punchcards.

And don't be hatin on TI-BASIC I've seen it perform miracles when you put enough faith (and blood/tears/animal sacrifice) into it

Ah, a meme. I didn't realize it was a meme...*facehoof*.

 

I'm not hating really, I just don't like anything that claims it is basic or a type of basic, because I don't like basic. It was never meant for anything more than a learning language and it should stay that way. Basic is only good for quick calculator scripts; and it's not Basic that's good, it's the math functions on the calc that give Basic power.

Share this post


Link to post
Share on other sites

Ah, a meme. I didn't realize it was a meme...*facehoof*.

Yep, it's an old one, and I guess that after all these years I have been subconsciously waiting for someone to mention machine code. Guess that goes to show just how meaningless and full of false pride my internet life is XD

 

The only thing TI-BASIC means to me is nostalgia: all those days sitting in class, not paying attention and making stupid little games like pong and snake (both of which do not play well on an 8x16 grid or whatever it was). Of course it's terrible, but it made me feel POWERFUL :)

Share this post


Link to post
Share on other sites

The only thing TI-BASIC means to me is nostalgia: all those days sitting in class, not paying attention and making stupid little games like pong and snake (both of which do not play well on an 8x16 grid or whatever it was). Of course it's terrible, but it made me feel POWERFUL :)

Sorry for bashing TI-BASIC then :). Nostalgia is powerful. Winston Churchill would listen to music, then not listen to that piece for a year, then listen to it again and be transported back to that time of his life. I do that too. Different music that I listen to at different times of my life, then I don't listen to it for awhile, and when I come back it hits me with power. I repeat: Nostalgia is powerful, cherish that feeling. Just make sure to still live in the present :).

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.