Jump to content
Banner by ~ Ice Princess Silky

C++ questions about strings


pocketshotgun

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!

Link to comment
Share on other sites

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
Link to comment
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.

  • Brohoof 1
Link to comment
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
Link to comment
Share on other sites

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
Link to comment
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.

Link to comment
Share on other sites

  • 3 weeks later...

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.

  • Brohoof 1
Link to comment
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

Link to comment
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.

Link to comment
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 :)

  • Brohoof 1
Link to comment
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 :).

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Join the herd!

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...