CS253

CS253: Software Development with C++

Spring 2017

String Literals

See this page as a slide show

String Literals

CS253 String Literals

Literals

Literals are constants, like 42, 1.2e-24, 'x', "foo", true, or nullptr.

This is a char: 'X'.
This is a C-style string literal: "alpha beta gamma".
(single quotes for a single character)

C++ 2011 has no std::string literals. C++ 2014 has "foobar"s, with the trailing s, but we won’t discuss those.

String Literals

A "string literal" is an anonymous array of characters. These are equivalent:

cout << "abc123" << '\n';
abc123


const char make_up_a_name[] = "abc123";
cout << make_up_a_name << '\n';
abc123

const char make_up_a_name[] = "abc123";
const char *p = &make_up_a_name[0];
cout << p << '\n';
abc123

Comparing C-Style Strings

if ("beta" < "alpha")   // BAD CODE
    cout << "This is really quite surprising!\n";
c.cc:1: warning: comparison with string literal results in unspecified behavior
This is really quite surprising!

Comparing C-style strings properly.

To compare C-style strings, use the function strcmp. It has a peculiar return value. strcmp(a,b) returns:

Why are you even considering using C-style strings?

Comparing C++ std::strings

To compare C++ std::string values, or to compare a std::string with a C-style string, use the usual operators:

    < > <= >= == !=

Only Java geeks use std::string::compare(), which has the same three-way return value as strcmp.

Modified: 2017-02-04T17:46

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building