File: stringcompare2.cc

package info (click to toggle)
c%2B%2B-annotations 13.02.02-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,576 kB
  • sloc: cpp: 25,297; makefile: 1,523; ansic: 165; sh: 126; perl: 90; fortran: 27
file content (48 lines) | stat: -rw-r--r-- 1,845 bytes parent folder | download | duplicates (10)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    #include <iostream>
    #include <string>
    using namespace std;

    int main()
    {
        string stringOne("Hello World");

            // comparing from a certain offset in stringOne
        if (!stringOne.compare(1, stringOne.length() - 1, "ello World"))
            cout << "comparing 'Hello world' from index 1"
                    " to 'ello World': ok\n";

            // the number of characters to compare (2nd arg.)
            // may exceed the number of available characters:
        if (!stringOne.compare(1, string::npos, "ello World"))
            cout << "comparing 'Hello world' from index 1"
                    " to 'ello World': ok\n";

            // comparing from a certain offset in stringOne over a
            // certain number of characters with a second C-string
            // This fails, as 3 chars in stringOne starting at
            // index 6 are compared with "World"
        if (!stringOne.compare(6, 3, "World"))
            cout <<
            "comparing 'Hello World' from index 6 over"
            " 3 positions to 'World and more': ok\n";
        else
            cout << "Unequal (sub)strings\n";

            // This one will report a match, as only 5 characters are
            // compared of the  source and target strings
        if (!stringOne.compare(6, 5, "World and more", 0, 5))
            cout <<
            "comparing 'Hello World' from index 6 over"
            " 5 positions to 'World and more': ok\n";
        else
            cout << "Unequal (sub)strings\n";
    }
    /*
            Generated output:

        comparing 'Hello world' from index 1 to 'ello World': ok
        comparing 'Hello world' from index 1 to 'ello World': ok
        Unequal (sub)strings
        comparing 'Hello World' from index 6 over 5 positions to
                    'World and more': ok
    */