C++ Tutorial: Strings and C-Strings

GFreak45

I didnt slap you, i high 5'd your face.
Reaction score
130
Uses: Getting Started and Functions and Variables

Strings:

Strings in C++ are an array of 1 byte numbers (characters). As C++ is an object oriented program there is a simple class that handles strings for you. You can access this class by including the string header. The string class manages sizes, re-sizing, appending, concating, and assigning string values.

The string class has a few constructors:
  • Default, initializes an empty string (no characters)
  • Overloaded, takes a c-string ("string inside quotes or array of characters")
  • Overloaded, takes a string (copies the string)
Useage examples:
Code:
string Name = "John"; // can also be written like so: string Name ("John")
 
string Nothing;
 
string NameCopy = Name;
The string class also comes with a few interesting operators:
  • operator = - assignment operator, changes one string's array of characters to equal another string's array, or a c-string
  • operator += - append operator, adds one string on to the end of the first
  • operator + - concatenate string operator, combines 2 strings and returns one
  • operator [] - allows you to attain the character in that position of the array
Useage Example:
Code:
string One = "a"; //One = "a"
 
One += "bcd"; //One = "abcd"
 
string Two = One;
One = (Two + "efg"); //One = "abcdefg"
 
One[0] = "1"; // One = "1bcdefg"
There are also a few great utility functions that come with the string class:
  • size - the ammount of characters in the string
  • substr - substring, a piece of the original string between 2 indeces
  • replace - replaces part of a string
  • getline - static, gets an entire line of an iostream (cin, fstreams, etc)
Useage examples:
Code:
string Sentence = "This is a sentence.";
 
string Word = Sentence.substr(0, 4); //start position, length - "This"
 
Sentence.replace(0, 0, Word);
/* replaces the substring with the given string, since this is a substring of 0 size
at place 0, it just inserts Word into the beginning of Sentence,
now Setence = "ThisThis is a sentence." */
Getline is a little more complex:
Code:
string line;
while (cin.peek() == '\n') cin.ignore();
getline(cin, line);
getline takes an iostream (cin or a file stream) and reads from the current position in the stream until it runs into a '\n' (new line). What it does not take into account, is that when you use the >> (get formated data) operator, a delimiter is left on the end, be it a space, a newline or a tab, therefore we need to make sure tha there are no hanging newlines before we get each line, that is the: while (cin.peek() == '\n') cin.ignore(), which checks if the next character to get is a newline without removing it, then if it is, it removes it via cin.ignore()

Full useage example:
Code:
#include <iostream>
#include <string>
 
using namespace std;
 
int main ()
{
    string name;
    char again = 'y';
    while (again != 'n')
    {
        cout << "What is your name? ";
        while (cin.peek() == '\n') cin.ignore();
        getline(cin, name);
        cout << "So your name is " << name << "\n"
            << "How old are you? ";
        int age = 0;
        cin >> age;
        cout << "So your name is " << name << " and you are " << age << " years old.\n"
            << "Would you like to input someone elses information? (y/n): ";
        cin >> again;
        cout << "\n";
    }
    cout << "\n";
    system("Pause");
    return 0;
}
C-Strings:

C-Strings are used in C and a little in C++, they were used in C because Object Oriented Programming had not taken a foothold yet. A C-String is an array of characters, as simple as that. A string can be initialized via: string s = "some sentence"; However, a C-String is initialized like so:
Code:
char s[] = { 's', 'o', 'm', 'e', ' ', 's', 'e', 'n', 't', 'e', 'n', 'c', 'e', '\n' };
The same way an array is initialized, but with characters rather than quotes, a character has the ' character around it to reference a number (UTF8 code) that represents that character, for instance '0' is the same as 31, so this is really just an array of numbers. There are a few interesting ways to interact with c-strings:
  • printf - prints the c-string (like cout) "print formated data"
  • scanf - gets information from the iostream
  • fprintf - prints information to a file (used the same as printf)
  • fscanf - file scan
  • We also gain use of the iostream::getline function (cin.getline)
  • The std::string::c_str function can get a constant C-String from any string (string.c_str)
In order to use these functions you must include the cstdio.h library
Useage Examples:
Code:
char s[] = { 's', 'o', 'm', 'e', ' ', 's', 'e', 'n', 't', 'e', 'n', 'c', 'e', '\n' };
 
printf("%s \n", s); //%s is the formatted data type
 
int input;
scanf("%d", &input);
/* %d is the signed int type, the & operator means address of
(so the scanf can edit the value of input, not needed with arrays) */
fscanf and fprintf are the same but interacting with files, for more information on printf and scanf click those links.

The getline function is somewhat like the static getline, but it is meant for a C-String.
Code:
#include <cstdio.h>
#include <iostream>
 
using namespace std;
 
int main ()
{
    char name[30];
    char again = 'y';
    while (again != 'n')
    {
        printf("%s", "What is your name? ");
        scanf("%s", name);
        printf("%s", "So your name is ");
        printf("%s \n", name);
        printf("%s", "How old are you? ";
        int age = 0;
        scanf("%d", &age);
        printf("%s", "So your name is ");
        printf("%s", name);
        printf("%s", " and you are ");
        printf("%d", &age);
        printf("%s \n", " years old.");
        printf("%s", "Would you like to input someone elses information? (y/n): ");
        scanf("%c", &again);
        printf("%s \n", "");
    }
    printf("%s \n", "");
    system("Pause");
    return 0;
}
The output of both full useage examples should be the same.
 

GetTriggerUnit-

DogEntrepreneur
Reaction score
129
I'm a bit lost with C-String. You say they must be initialized like an array, isn't there a way to initialize with quotes like
Code:
char* a = "I like trains.";
 

GFreak45

I didnt slap you, i high 5'd your face.
Reaction score
130
yes, but that is not its own instance. Basically, if you use that sentence again exactly as put there then it will use the same reference in memory. So if you do something like this:
Code:
char* a = "I like trains.";
a[3] = s; //or scanf("%s", a);
it will modify that array in memory for any other values of the same string, ie:
Code:
char* otherString = "I like trains."; //after the first code
//otherString actually equals "I lske trains."
so, yes that will work, but it should not be modified unless you create an entirely new array to hold the values in.
 
General chit-chat
Help Users
  • No one is chatting at the moment.
  • The Helper The Helper:
    Happy Sunday!
    +1
  • The Helper The Helper:
    I will be out of town until Sunday evening
    +1
  • The Helper The Helper:
    I am back! Did you miss me LOL
    +1
  • jonas jonas:
    where did you go?
  • The Helper The Helper:
    Jefferson TX on a Paranormal Investigation of a haunted bed and breakfast - I got some friends that are paranormal investigators and they have an RV and do YouTubes
    +1
  • The Helper The Helper:
    It was a lot of fun. The RV was bad ass
  • jonas jonas:
    That sounds like fun!
    +1
  • The Helper The Helper:
    it was a blast!
  • The Helper The Helper:
    I am going to post the Youtube of the investigation in the forums when it is ready
    +1
  • jonas jonas:
    cool!
  • vypur85 vypur85:
    Sounds cool TH.
  • tom_mai78101 tom_mai78101:
    I was on a Legend of Zelda marathon...
  • tom_mai78101 tom_mai78101:
    Am still doing it now
    +1
  • jonas jonas:
    which one(s) are you playing?
  • jonas jonas:
    I played a little bit of the switch title two weeks ago and found it quite boring
  • The Helper The Helper:
    just got back from San Antonio this weekend had the best Buffalo Chicken Cheesesteak sandwhich in Universal City, TX - place was called Yous Guys freaking awesome! Hope everyone had a fantastic weekend!
    +1
  • The Helper The Helper:
    Happy Tuesday!
  • The Helper The Helper:
    We have been getting crazy numbers reported by the forum of people online the bots are going crazy on us I think it is AI training bots going at it at least that is what it looks like to me.
  • The Helper The Helper:
    Most legit traffic is tracked on multiple Analytics and we have Cloud Flare setup to block a ton of stuff but still there is large amount of bots that seem to escape detection and show up in the user list of the forum. I have been watching this bullshit for a year and still cannot figure it out it is drving me crazy lol.
    +1
  • Ghan Ghan:
    Beep boop
    +1
  • The Helper The Helper:
    hears robot sounds while 250 bots are on the forum lol
  • The Helper The Helper:
    Happy Saturday!
    +1
  • The Helper The Helper:
    and then it was Thursday...
    +1

    The Helper Discord

    Members online

    No members online now.

    Affiliates

    Hive Workshop NUON Dome World Editor Tutorials

    Network Sponsors

    Apex Steel Pipe - Buys and sells Steel Pipe.
    Top