Home  >  Article  >  Java  >  In-depth analysis of strings in C++ and JAVA

In-depth analysis of strings in C++ and JAVA

高洛峰
高洛峰Original
2017-01-19 15:04:591165browse

All string classes originate from C language strings, and C language strings are arrays of characters. There are no strings in C language, only character arrays.
Let’s talk about C++ strings: C++ provides two types of string representations: C-style strings and the string type introduced by standard C++. It is generally recommended to use the string type, but in practice you still have to use the old C-style strings.
1.C-style strings: C-style strings originated from C and were extended in C++. The string is stored in a character array, for example:
        const char *str = “zhangdan”; (don’t forget the last \0)
                                                                                                          const char *str = “zhangdan”; (Don’t forget the last \0)
                                                                      const char *str = “zhangdan”; When operating strings, you only need to operate pointers. For example:
const char * str = "zhangdan"; const char *p = str; Then just operate on p.
2. Standard C++ string type: If you use it, you must first introduce the header file: #include98c455a79ddfebb79781bff588e7b37e
The standard string type provided in C++ provides the following operations:
(1).Support Initialize a string object with a sequence of characters or a second string. C-style strings do not support initializing another string with another string.
(2). Supports copying between strings. C-style strings are implemented through the strcpy() function.
(3). Supports read and write access to single characters. For C-style strings, individual characters can only be accessed by dereferencing or by subscripting.
(4). Supports equality comparison of two strings. For C-style strings, comparison is implemented through the strcmp() function.
(5). Supports the connection of two strings. For C-style strings, use the strcpy() function to copy to a new instance, and then use strcat() to connect the two strings. For example:
string str1 = "111111", str2 = "222222";
string str3 = str1 + str2;
(6). Supports querying the length of the string: string s ("XXXXXXX") ; str.size() is the length of the string.
Mutual conversion: const char * str = str2.c_str(); //The string type cannot be assigned directly to a character array, but a character array can be assigned to a string type: such as: const char *str = "zhangdan"; string str2 = str;


Input of C++ string class
(1) Method one: Same as method one of C string input.
(2) Method 2: Use the getline function.
For example: string a;
getline(cin,a);


Conversion from string to number
The atoi function gets a C string parameter and returns the corresponding int value . If the parameter does not correspond to an int value, atoi will return 0. The atoi function is in the library whose file is cstdlib. If the number is too large to be converted to an int value, you can use atol to convert the string to a long value.
For example:
atoi("1234"); //Returns the integer 1234
atoi("#123"); //Returns 0
The common methods of strings in C++ will not be introduced one by one. , introduce some commonly used ones: begin(), end(), append(), etc.
2: String in JAVA: In JAVA, String does not belong to the 8 basic types, so String is an object, and the default value is null
For example: String str = new String(); and String str = new String(""); means to construct an empty string (understand the difference between null and "").

Look at the following code:

String str = "xxx";
String str2 = new String("xxx");
System.out.println(str == str2);
System.out.println(str.equals(str2));


The result is:
false

true


Why? In JAVA, == is a comparison of addresses, and equals is a comparison of contents. Why are the addresses different?
First introduce the concept of constant pool:


The constant pool (constant pool) refers to some data that is determined during compilation and saved in the compiled .class file. It includes constants in classes, methods, interfaces, etc., as well as string constants.
When we assign a string to a string variable, such as String str = "xxxx"; At this time, first go to the constant pool to find whether there is a copy of the string "xxxx". If there is, Point the address of str to the address of the string constant "xxxx" in the constant pool. If it does not exist, create the string constant of "xxxx" in the constant pool. And new String("xxxx") is placed in the heap memory and has its own memory space. So the addresses are different when compared.

Look at the following piece of code:

String str = "zhang";
String str2 = "peng";
String str3 = "zhangpeng";
String str4 = "zhangpeng"
str += str2;
System.out.println(str == str3);
System.out.println(str3 == str4)


The result is:
true
true


Why?

First of all, we need to know that Java will ensure that there is only one copy of a string constant. ###

Because the "zhangpeng" in str3 and str4 in the example are both string constants, they are determined at compile time, so str3==str4 is true; and "zhang" and "peng" are also characters String constants, when a string is concatenated by multiple string constants, it must itself be a string constant, so str2 is also parsed into a string constant at compile time, so str2 is also in the constant pool. "A reference to.

The difference between String and StringBuffer in JAVA:

String:
is an object that is not a primitive type.
is an immutable object. Once it is created, it cannot be modified. The value.
Modifications to the existing String object are to create a new object and then save the new value in it.
String is a final class, that is, it cannot be inherited.
StringBuffer:
It is a mutable object. When it is modified, the object will not be re-established like String.
It can only be created through the constructor,
StringBuffer sb = new StringBuffer();
Cannot Pay it through the payment symbol.
sb = "xxxxx";
After the object is created, memory space will be allocated in the memory and a null will be initially saved. Pay the value to StringBuffer
You can use its append method.
sb.append("hello");
StringBuffer is more efficient than String in string connection operations:
String str = new String("xxx") ;
str += "xx";
The processing steps are actually to create a StringBuffer, then call append(), and finally
then StringBuffer toSting();
In this case, the String connection The operation has some additional operations than StringBuffer, so it is slower.

Ask a question: Why is StringBuffer so efficient, so do we still need String?
If you don’t know, check it out. The direction is the constant pool.

Python string:
Python is a powerful scripting language that does not need to define a type when defining a string. Python strings usually have single quotes ('...'), double quotes ("..."), triple quotes ("""...""") or ('''...''') Surrounded by triple quotes, the string can be composed of multiple lines and can generally represent a large narrative string. There is basically no difference in use, but double quotes and triple quotes ("""...""") can contain single quotes, and triple quotes ('''...''') can contain double quotes, but not Requires escaping. When special escaping is needed, you can use '\'
Python also has many string manipulation functions. Specifically, you can use dir, which is similar to C++ and java.

The above is the entire content of this article, I hope it will be helpful to everyone's study.

For more in-depth analysis of string-related articles in C++ and JAVA, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn