Classes string and wstring. Part 5

c ++ beginners, the string class, wstring class, containers STL C ++ , Standard Template Library, c ++ containerThe string class C ++ standard library is well-known and readily use. But not everyone and not always think about the fact, the class string, with some differences in the details - this is the container vector: vector<char> . True, he supplemented certain features (but this code and you will be able to write):

  • Method size() duplicated by length(). They are completely identical, for reasons of convenience. Just to have a more natural string length, what size;

  • Defined overloaded operators +, += that return concatenation (an association) strings;

  • Defined constructor, initializes string when you create the initial value of the character string in the format ASCIIZ (char* - A pointer to a character array in C-style ending in zero);

  • Defined method c_str(), which returns a pointer to the internal contents of the string in the format ASCIIZ. Since this is the inner meaning, it can be used, but do not try to change it. This will not end well.

In all behave exactly the same strings as the rest of the vector, and applicable to them all operations on vectors. Understanding, that is a class string (vector<char>) can afford to create a number of unexpected effects. For example, because the null character is not vector<char> no special meaning (Unlike the C-string), then it is also quite possible to "push" to the end string. It is thus possible to place a single variable string a whole array of C-strings, or even the whole text.

Here is, how to put in a similar way all set environment variables (environment) operating system one variable string:

Note: Here, we used one of the more permissible forms the main functions of the program main() – 3-m parameter which is an array of pointers strings (char*) environment variables (environment). A sign of the end of an array of strings envp It is a pointer NULL (those. Operating System Documentation).

Result:the string class, wstrting class, containers STL C ++ , Standard Template Library, c ++ container

What about the type of wstring? wstring - The equivalent of vector<wchar_t> , vector "broad", localized characters, representing the international character encoding Unicode. Analysis of contents (Search, word selection, string breaks, etc.) Russian-speaking or any other string (Chinese example) It can only be done in the format wtring (not string). It is necessary to pre-set the correct locale for the program (the default locale “Exist” It assumes only ASCII characters in 7-bit representation). For IO wstring offered streams, respectively wcin and wcout, instead cin and cout, intended for string. It is written as a reminder.

By way of illustration, consider a localized string analysis wstring on the subject of, whether it is a palindrome.

Spaces and punctuation are ignored for comparisons:

The letter L in front of a character constant is, that the string contains more , written to a wide character wchar_t

Result:the string class, wstrting class, containers STL C ++ , Standard Template Library, c ++ container

Localization - this is a completely different topic, which would lead us away from our main theme. Discussion of localization and wide characters in C / C ++ can be read here.

Probably, this part is relevant to note the following facts, relating to all types of STL containers. When you create a container constructor without parameters, creates an empty container, More not containing any element (blank for future fill the container). The size of the container (method size(), or length() for period) zero. But more effective, in terms of performance, Inspecting containers for vacuum method empty(), which is present in all types of containers.

Newsletter of programming:

Classes string and wstring. Part 5
3 (60%) 1 vote

About Olej

practical experience about software development 40 years. Teacher Global Logic international software company. IBM Developer Works Permanent author of publications. Scientific editor of the computer literature publishing house "Symbol-Plus", St. Petersburg.

5 thoughts on “Classes string and wstring. Part 5

  1. Thanks to the author of the article.
    But I have a question – Why do not you enter into a condition statement in braces? It's not very readable. For example:

    or so:

    The second option is uniquely clearer…

    1. because, that the issue of a code format – a matter of taste, preferences, and in this respect there are many different opinions.

      P.S. The young fools (such as Habrahabr) proudly calls it kodestayl and make this fetish, end in itself. But the code is not written for the aesthetic pleasure (how to place parenthesis prettier), and for, so that it perfectly have worked. But this, that it engineering specialty, rather than aesthetic fun, in recent years 10 somehow have forgotten.

      1. Любой дурак может написать код, понятный компьютеру. Хороший программист пишет код, понятный человеку.
        Мартин Фаулер

        Видите лиесли Вы пишете код для компьютера, для достижения собственных целей и для собственного удовлетворениято пожалуйста, никто не запрещает и не сказал бы Вам ничего против, но почему-то этот мне и людям приходится видеть этот код, читать его
        В последнее время чтение кода людьми и понимание написанного играет ключевую роль в написании программных систем, люди меняются, а разрабатывать продукт нужно продолжать, хотя конечно, как я и сказал ранее, это не относится если Вы пишете код только в своём проекте над которым не работают другие люди.

        в данной ситуации, действительно лишь дело вкуса ставить скобочки или нет, я пишу лишь по поводу Вашего ответа.

      2. Dmitriy, ещё раз повторюдля лучшей усвояемости: exist несколько разных стилей форматирования кода C/C++. И ни один из них не лучше и не хуже остальных.
        Мне довелось работать в нескольких разработческих софтверных компаниях, у которых были совершенно разные корпоративные требования (кодестайл). Так что стиль нужно выбирать тот, который используется в текущем проекте.

Leave a Reply

Your email address will not be published. Required fields are marked *