Java中的字符串

弦乐 (Strings)

Strings are sequences of characters. In Java, a String is an Object. Strings should not be confused with char as characters are literally 1 value rather than a sequence of characters. You can still use 1 value within a String, however it is preferred to use char when you are checking for 1 character.

字符串是字符序列。 在Java中, StringObject 。 字符串不应与char混淆,因为字符实际上是1值,而不是字符序列。 您仍然可以在字符串中使用1值,但是在检查1个字符时最好使用char

String course = "FCC";
System.out.println(course instanceof Object);

Output:

输出:

true

You can create a String Object in the following ways:

您可以通过以下方式创建字符串对象:

  1. String str = "I am a String"; //as a String literal

    String str = "I am a String"; //as a String literal

  2. String str = "I am a " + "String"; //as a constant expression

    String str = "I am a " + "String"; //as a constant expression

  3. String str = new String("I am a String"); //as a String Object using the constructor

    String str = new String("I am a String"); //as a String Object using the constructor

You might be thinking: What’s the difference between the three?

您可能在想:这三个之间有什么区别?

Well, using the new keyword guarantees that a new String object will be created and a new memory location will be allocated in the Heap memory (click here to learn more). String literals and constant String expressions are cached at compile time. The compiler puts them in the String Literal Pool to prevent duplicates and improve memory consumption. Object allocation is expensive and this trick increases performance while instantiating Strings. If you use the same literal again, the JVM uses the same object. Using the contructor like above is almost always a worse choice.

好吧,使用new关键字可以保证将创建一个新的String对象,并在Heap内存中分配一个新的内存位置(单击此处以了解更多信息) 。 字符串文字和常量字符串表达式在编译时进行缓存。 编译器将它们放入“字符串文字池”中,以防止重复并改善内存消耗。 对象分配是昂贵的,并且此技巧可在实例化字符串时提高性能。 如果再次使用相同的文字,那么JVM将使用相同的对象。 像上面那样使用构造器几乎总是一个较差的选择。

In this code snippet, how many String objects are created?

在此代码段中,创建了多少个String对象?

String str = "This is a string";
String str2 = "This is a string";
String str3 = new String("This is a string");

The answer is: 2 String objects are created. str and str2 both refer to the same object. str3 has the same content but using new forced the creation of a new, distinct, object.

答案是:2创建了字符串对象。 strstr2都引用相同的对象。 str3具有相同的内容,但是使用new强制创建新的,不同的对象。

When you create a String literal, the JVM internally checks, what is known as the String pool, to see if it can find a similar (content wise) String object. If it finds it, it returns the same reference. Otherwise, it just goes ahead and creates a new String object in the pool so that the same check can be performed in the future.

创建String文字时,JVM在内部检查称为String pool ,以查看它是否可以找到类似的(内容明智的)String对象。 如果找到它,则返回相同的引用。 否则,它将继续并在池中创建一个新的String对象,以便将来可以执行相同的检查。

You can test this using the swallow, fast Object comparison == and the implemented equals().

您可以使用快速,快速的对象比较==和实现的equals()

System.out.println(str == str2); // This prints 'true'
System.out.println(str == str3); // This prints 'false'
System.out.println(str.equals(str3)); // This prints 'true'

Here’s another example on how to create a string in Java using the different methods:

这是另一个有关如何使用不同方法在Java中创建字符串的示例:

public class StringExample{  

   public static void main(String args[]) {  
      String s1 = "java";  // creating string by Java string literal  
      char ch[] = {'s','t','r','i','n','g','s'};  
      String s2 = new String(ch);  // converting char array to string  
      String s3 = new String("example");  // creating Java string by new keyword  
      System.out.println(s1);  
      System.out.println(s2);  
      System.out.println(s3);  
   }
}
比较字符串 (Comparing Strings)

If you want to compare the value of two String variables, you can’t use ==. This is due to the fact that this will compare the references of the variables and not the values that are linked to them. To compare the stored values of the Strings you use the method equals.

如果要比较两个String变量的值,则不能使用==。 这是由于这样的事实,它将比较变量的引用而不是链接到它们的值。 要比较字符串的存储值,请使用equals方法。

boolean equals(Object obj)

It returns true if two objects are equal and false otherwise.

如果两个对象相等,则返回true,否则返回false。

String str = "Hello world";
String str2 = "Hello world";

System.out.println(str == str2); // This prints false
System.out.println(str.equals(str2); // This prints true

The first comparison is false because ”==” looks at the references and they aren’t the same.

第一次比较是错误的,因为“ ==”查看的是引用,但它们并不相同。

The second comparison is true because the variables store the same values. In this case “Hello world”.

第二个比较是正确的,因为变量存储相同的值。 在这种情况下是“ Hello world”。

We have several inbuilt methods in String. The following is an example of the String Length() method .

我们在String中有几个内置方法。 以下是String Length()方法的示例。

public class StringDemo {

   public static void main(String args[]) {
      String palindrome = "Dot saw I was Tod";
      int len = palindrome.length();
      System.out.println( "String Length is : " + len );
   }
}

This will result in - String Length is : 17

这将导致- String Length is : 17

The answer is: 2 String objects are created. Notes

答案是:2创建了字符串对象。 笔记

  1. String methods use zero-based indexes, except for the second argument of substring().

    字符串方法使用从零开始的索引,但substring()的第二个参数除外。

  2. The String class is final - it’s methods can’t be overridden.

    String类是最终的-不能覆盖其方法。
  3. When the String literal is found by JVM, it is added to string literal pool.

    JVM找到字符串文字后,会将其添加到字符串文字池。
  4. String class posses a method name length(), while arrays have an attribute naming length.

    字符串类具有方法名称length() ,而数组具有属性命名长度。

  5. In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable. Once string object is created its data or state can’t be changed but a new string object is created.

    在Java中,字符串对象是不可变的。 不可变只是意味着不可更改或不可更改。 创建字符串对象后,其数据或状态便无法更改,但会创建一个新的字符串对象。

String Length

弦长

The “length” of a string is just the number of chars in it. So “hi” is length 2 and “Hello” is length 5. The length() method on a string returns its length, like this:

字符串的“长度”就是其中的字符数。 因此,“ hi”是长度2,“ Hello”是长度5。字符串上的length()方法返回其长度,如下所示:

String a = "Hello";
int len = a.length();  // len is 5
也可以在String上使用的其他比较方法是: (Other comparison methods which can also be used on the String are :)
  1. equalsIgnoreCase() :- compares the string without taking into consideration the case sensitivity.

    equalsIgnoreCase():-比较字符串,而不考虑大小写敏感性。
String a = "HELLO";
String b = "hello";
System.out.println(a.equalsIgnoreCase(b));   // It will print true
  1. compareTo :- compares the value lexicographically and returns an integer.

    compareTo:-按字典顺序比较该值并返回一个整数。
String a = "Sam";
String b = "Sam";
String c = "Ram";
System.out.println(a.compareTo(b));       // 0
System.out.prinltn(a.compareTo(c));       // 1 since (a>b)
System.out.println(c.compareTo(a));       // -1 since (c<a)

翻译自: https://www.freecodecamp.org/news/strings-in-java/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值