element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Code Exchange
  • Technologies
  • More
Code Exchange
Blog C++ Tutorial - Strings
  • Blog
  • Forum
  • Documents
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Code Exchange to participate - click to join for free!
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: oneleggedredcow
  • Date Created: 8 May 2013 3:15 AM Date Created
  • Views 1296 views
  • Likes 0 likes
  • Comments 2 comments
  • raspbpi
  • code_exchange
  • Code Exchange
  • learn++
  • programming
  • raspberry_pi
  • code
  • rpi
  • c++
  • learnc++
Related
Recommended

C++ Tutorial - Strings

oneleggedredcow
oneleggedredcow
8 May 2013

Introduction

In the previous tutorial, we talked about reading and writing binary data to a file.

 

In this tutorial, we are going to talk about strings.  Strings are a way of storing and manipulating text within C++.

Code

Let’s jump right in and create a string:

 

#include <iostream>

#include <string>


 

using namespace std;


 

int main()

{

string helloRpi("Hello Raspberry Pi");

 

cout << helloRpi << endl;


 

return 0;

}


As you can probably guess from the code sample above, string is a class that is defined in the <string> library.  (The parenthesis after the variable name was the hint that makes me guess that string is a class.)  Another way to create the string would be like this:

 

string helloRpi = "Hello Raspberry Pi";


Since string is a class, it has many methods on it that help manipulate the string.  One such method is the substr, which grabs a piece of the original string.  So, if we wanted to extract the word hello from the previous phrase we could do this:

 

string hello = helloRpi.substr(0, 5);


We can also compare two strings to see if they are equal.  Take the following code example:

 

int main()

{

string hello1 = "Hello";

string hello2 = "hello";


 

if (hello1 == hello2)

{

cout << "Equal" << endl;

}

else

{

cout << "NOT Equal" << endl;

}


 

return 0;

}


Do you think that hello1 and hello2 are equal to one another?  They are not equal to one another because hello1 has a capital H and hello2 has a lowercase h.  Since they aren’t exactly the same, they aren’t considered equal.

 

This brings up an interesting question.  If they aren’t equal, than which one comes first?  Meaning that if I did a less than operation on them, which one has a “lower” value?  The code looks like this:

 

if (hello1 < hello2)

{

cout << hello1 << ", " << hello2 << endl;

}

else

{

cout << hello2 << ", " << hello1 << endl;

}


When you run the following code, the capital Hello is first, followed by the lowercase hello.  Why is that?  The answer goes back to the ASCII table.  In order to determine which word comes first, each character is compared one by one. If the characters are the same then it moves to the next one.  If they are different, the word that corresponds to the character with the lower ASCII value is the lower one.  Since H has an ASCII value of 72 and h has an ASCII value of 104 that means that Hello comes before hello.  This comes in handy when trying to alphabetize a list of words.  Always remember that the default comparisons put the words in ASCII order, which isn’t necessarily alphabetical order, because all capitalized words will come before all lowercase words.

 

Another common thing to do is to append one string to another (sometimes called concatenation).  This can be done using the append method:

 

string foo = "foo";

string bar = "bar";

string cat = foo.append(bar);


 

cout << cat << endl;


Or by simply adding the strings together:

 

string foo = "foo";

string bar = "bar";

string cat = foo + bar;


 

cout << cat << endl;


Ok, now for a little fun. Using what we know about stings, we can create a simple program that answers the fundamental question: why? Here’s what the code looks like:

 

#include <iostream>

#include <string>

#include <ctime>


 

using namespace std;


 

int numSubjects = 4;

string subjects[] = { "The universe",

"I",

"The man in the white hat",

"A garden gnome" };


 

int numVerbs = 2;

string verbs[] = { "wants",

  "loves" };


 

int numComplements = 4;

string complements[] = { "string cheese",

    "cake",

    "bicycles",

    "a Raspberry Pi" };


 

int numCanned = 5;

string canned[] = { "Why not?",

   "I said so",

   "C++ is the greatest language of all time",

   "That is how he wants it",

   "Boom goes the dynamite" };


 

string why()

{

int chance = rand() % 10;


 

string sentence;

if(chance < 7)

{

// Random

string subject = subjects[rand() % numSubjects];

string verb = verbs[rand() % numVerbs];

string complement = complements[rand() % numComplements];


 

sentence = subject + " " + verb + " " + complement;

}

else

{

sentence = canned[rand() % numCanned];

}


 

return sentence;

}


 

int main()

{

    srand((unsigned int) time(NULL));

cout << why() << endl;


 

return 0;

}


The why function randomly generates a simple sentence as the answer to the question.  Feel free to tinker with it and see what crazy answers you can get it to produce!

Summary

In this tutorial, we talked about strings, which are a way to store text in a program.  We also discussed ways to manipulate strings, as well as created a small program to answer the age old question of why.

 

In the next tutorial, we will be discussing constants.  Constants are a way of making sure that the value of something never changes. Appropriate use of constants is one of the topics that separates a good programmer from a great one in my opinion.

 

If you have any questions or comments about what was covered here, post them to the comments.  I watch them closely and will respond and try to help you out.

Tutorial Index

01 - Hello Raspberry Pi

02 - Reading User Input

03 - If Statement

04 - For Loops

05 - While Loops

06 - Functions

07 - Data Types

08 - Arrays

09 - Structures

10 - Classes

11 - Pointers

12 - Dynamic Arrays

13 - Linked List

14 - Linked List Operations

15 - STL List/Vector

16 - Templates

17 - Inheritance

18 - File I/O

19 - Strings

20 - Constants

21 - Hash Tables

  • Sign in to reply
  • oneleggedredcow
    oneleggedredcow over 10 years ago in reply to Former Member

    Thanks for the comments!  I updated the post.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • Former Member
    Former Member over 10 years ago

    Interesting lesson. A couple of observations:

     

    1) I noticed that the line:

    string cat = foo.append(bar);

    also appends bar to foo, such that both cat and foo become foobar


    2) In your sentence game, I kept getting "The man in the white hat loves a Raspberry Pi." over and over again. Fortunately, I remembered your lesson 3 and brought in

    #include <ctime>

     

    and then added the line

     

     

    srand((unsigned int) time(NULL));

     

     

    to your why() function right before

     

     

    int chance = rand() % 10;

     

    then I got a variety of results.

     

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube