Strings

В C ++, тип данных string обеспечивает необходимую абстракцию, чтобы позволить программистам работать со строками символов. В Java фактически образуют два отдельных класса.

В отличие от Java, C++ string тип не доступен для всех программ по умолчанию. Если C++ программа требует string тип, программист должен обратиться к библиотеке, которая определяет этот тип. Следующая распечатка иллюстрирует C ++ тип данных последовательности в действии.

 

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: #include <iostream>#include <string>#include <cstdlib> using namespace std; int main(int argc, char* argv[]) { string s1 = "first"; // Initialization string s2; s1 += " string"; // Concatenation s2 = s1; // Assignment cout << s1 << endl; // Stream output cout << s1.length() << endl; // Length return EXIT_SUCCESS;}Listing 3 string variables in use

 

The inclusion of the preprocessor directive found in line 2 in the above listing is necessary to allow the program access to the string data type. Notice also the various methods and functionality of the string variables that the example demonstrates. In line 9, a string literal initializes a string object. Lines 11 and 12 demonstrate concatenation and assignment. To display the contents of a string variable, we can use basic console output as shown in line 14. This listing demonstrates only some basic functionality of the string data type. Many other useful functions exist. Arrays C++ provides basic support for a sequence of homogeneous data objects through arrays. Both similarities and differences exist between Java arrays and arrays in C++. In Java, we can declare and initialize an array of ten ints using the following.
1: 2: 3: // declare and create two arrays of integersint[] javaArray1 = new int[10];int javaArray2[] = new int[10];
Listing 4 Arrays in Java

The C++ syntax equivalent to the above Java code looks similar, except for the use of the keyword new. The keyword new, in Java, creates an instance of an object. In C++, the keyword new has a different meaning, one that we address in 1.4.3 Dynamic Memory Management. The following listing demonstrates the declaration of an int array of size ten in C++.

1: 2: // declare and create an array of integersint cpp_array[10];
Listing 5 An array in C++

The double bracket ([]) in the declaration indicates that the line declares an array. Notice the placement of the double bracket ([]) in each of the examples. In Java, the double bracket can be placed after the name of the data type or after the name of the variable. In C++, it can only be placed after the name of the variable.

Accessing the elements stored in an array is done the same way in C++ as it is in Java. Both languages use the bracket operator ([]). A programmer encloses in brackets an index number of the element they wish to access. Indexing of arrays in C++, as in Java, begins with zero. This means that the first element of an array is accessed at index 0, the second element at index 1, the third element at index 2, and so on. The following listing demonstrates accessing the elements of a C++ array.

Включение директивы препроцессора, в линии 2, необходимо, чтобы позволить доступ программы к string data type. Заметьте также различные методы и функциональные возможности string переменных в примере. По линии 9, string инициализирует string объект. Линии 11 и 12 демонстрируют связь и назначение. Чтобы показать содержание переменной последовательности, мы можем использовать как показано в линии 14. Существуют много других полезных функций. Arrays C++ позволяет последовательностям гомогенных объектов данных выражать через массивы. И общие черты и различия существуют между Java массивами и массивами в C++. Сначала давайте рассмотрим синтаксис для объявления и инициализации массивов. В Java это можно сделать так:
1: 2: 3: // declare and create two arrays of integersint[] javaArray1 = new int[10];int javaArray2[] = new int[10];
Listing 4 Arrays in Java

C++ синтаксис, эквивалентный Java, за исключением использования нового ключевого слова. Новое ключевое слово, в Java, создает объект. В C++, у нового ключевого слова может быть различное значение см. 1.4.3 Dynamic Memory Management. Следующая распечатка демонстрирует объявление массива int в C++.

1: 2: // declare and create an array of integersint cpp_array[10];
Listing 5 An array in C++

Двойная скобка ([]) указывает, что в строке объявляется массив. Заметьте размещение двойной скобки ([]) в каждом из примеров. В Java двойная скобка может быть помещена после названия типа данных или после названия переменной. В C++, это может быть помещено только после названия переменной.

Обращение к элементам сохраненных в массиве, в C++ осуществляется аналогично, как и в Java. Оба языка используют оператор двойной скобки ([]). Программист записывает в скобках индекс элемента, означающий величину массива. Индексация массива в C ++, как в Java, начинается с нуля. Это означает, что первый элемент массива всегда имеет индекс 0, второй элемент индекс 1, третий элемент индекс 2, и так далее. Следующая распечатка демонстрирует вызов к элементам массива в C++.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: #include <iostream>#include <cstdlib> using namespace std; int main(int argc, char* argv[]) { int arr[25]; for (int i = 0; i < 25; i++) { arr[i] = i; } cout << "The first element equals: " << arr[0] << endl; cout << "The second element equals: " << arr[1] << endl; cout << "The last element equals: " << arr[24] << endl; return EXIT_SUCCESS;}Listing 6 Accessing elements of a C++ array

 

One inherent danger that exists in using C++ arrays is the lack of bounds checking. This is not the case in C++, since boundary checking of arrays is not supported. If we have an array of ten elements in C++, we can attempt to access the 12th, or 20th, or even 100th index of the array. Depending on a few different things, the program may or may not "crash" as a result of our out-of-bounds access. We can be sure, however, that the data we obtain from an out of bounds access will not be meaningful. The following listing shows an out-of-bounds array access in C++.

1: 2: int arr[10];cout << arr[11] << endl;
Listing 7 Out of bounds access

The code in the above listing, in the context of an actual C++ program, definitely compiles, and it may even run without error. This is clearly a dangerous practice, and one that we will always avoid.