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 Discord

      Staff online

      Members online

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top