java string_java string

java string

Java String is one of the most widely used class. Java String class is defined in java.lang package.

Java String is one of the most widely used classes. The Java String class java.langis defined in the package.

Java String ( Java String )

  • Basically, string is a sequence of characters but it’s not a primitive type.

    Basically, strings are sequences of characters, but not primitive types.
  • When we create a string in java, it actually creates an object of type String.

    When we create a string in Java, it actually creates an object of type String.
  • String is immutable object which means that it cannot be changed once it is created.

    Strings are immutable objects, which means they cannot be changed once created.
  • String is the only class where operator overloading is supported in java. We can concat two strings using + operator. For example "a"+"b"="ab".

    String is the only class in Java that supports operator overloading. We can use the + operator to concatenate two strings. For example "a"+"b"="ab".
  • Java provides two useful classes for String manipulation – StringBuffer and StringBuilder.

    Java provides two useful classes for String manipulation – StringBuffer and StringBuilder .

Let’s go ahead and learn more about Java String class.

Let's move on to learn more about the Java String class.

Different Ways to Create String

There are many ways to create a string object in java, some of the popular ones are given below.

There are many ways to create string objects in Java, some popular ones are listed below.

  1. Using string literal _

    This is the most common way of creating string. In this case a string literal is enclosed with double quotes.

    String str = "abc";


    When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.

    这是创建字符串的最常见方法。 在这种情况下,字符串文字用双引号引起来。

    String str = "abc";


    当我们使用双引号创建String时,JVM会在String池中查找是否以相同的值存储了其他String。 如果找到,它将仅返回对该String对象的引用,否则它将创建一个具有给定值的新String对象并将其存储在String池中。

  2. 使用新关键字 (Using new keyword)

    We can create String object using new operator, just like any normal java class. There are several constructors available in String class to get String from char array, byte array, StringBuffer and StringBuilder.

    String str  =  new String("abc");
    char[] a = {'a', 'b', 'c'};
    String str2  =  new String(a);

    就像任何普通的java类一样,我们可以使用new运算符创建String对象。 String类中有几个构造函数可用于从char数组,字节数组,StringBuffer和StringBuilder中获取String。

    String str  =  new String("abc");
    char[] a = {'a', 'b', 'c'};
    String str2  =  new String(a);

Java字符串比较 (Java String compare)

String class provides equals() and equalsIgnoreCase() methods to compare two strings. These methods compare the value of string to check if two strings are equal or not. It returns true if two strings are equal and false if not.

字符串类提供equals()equalsIgnoreCase()方法来比较两个字符串。 这些方法比较字符串的值以检查两个字符串是否相等。 如果两个字符串相等,则返回true否则返回false

package com.journaldev.string.examples;

/**
 * Java String Example
 * 
 * @author pankaj
 *
 */
public class StringEqualExample {

	public static void main(String[] args) {
		//creating two string object
		String s1 = "abc";
		String s2 = "abc";
		String s3 = "def";
		String s4 = "ABC";
		
		System.out.println(s1.equals(s2));//true
		System.out.println(s2.equals(s3));//false
		
		System.out.println(s1.equals(s4));//false;
		System.out.println(s1.equalsIgnoreCase(s4));//true
	}

}

Output of above program is:

上面程序的输出是:

true
false
false
true

String class implements Comparable interface, which provides compareTo() and compareToIgnoreCase() methods and it compares two strings lexicographically.

字符串类实现Comparable接口,该接口提供compareTo()compareToIgnoreCase()方法,并且按字典顺序比较两个字符串。

Both strings are converted into Unicode value for comparison and return an integer value which can be greater than, less than or equal to zero. If strings are equal then it returns zero or else it returns either greater or less than zero.

这两个字符串都转换为Unicode值以进行比较,并返回一个可以大于,小于或等于零的整数值。 如果字符串相等,则返回零,否则返回大于或小于零。

package com.journaldev.examples;

/**
 * Java String compareTo Example
 * 
 * @author pankaj
 *
 */
public class StringCompareToExample {

	public static void main(String[] args) {
		
		String a1 = "abc";
		String a2 = "abc";
		String a3 = "def";
		String a4 = "ABC";
		
		System.out.println(a1.compareTo(a2));//0
		System.out.println(a2.compareTo(a3));//less than 0
		System.out.println(a1.compareTo(a4));//greater than 0
		System.out.println(a1.compareToIgnoreCase(a4));//0
	}

}

Output of above program is:

上面程序的输出是:

0
-3
32
0

Please read this in more detail at String compareTo example.

请在String compareTo示例中详细阅读。

Java字符串方法 (Java String Methods)

Let’s have a look at some of the popular String class methods with an example program.

让我们用一个示例程序来看看一些流行的String类方法。

  1. 分裂() (split())

    Java String split() method is used to split the string using given expression. There are two variants of split() method.

    • split(String regex): This method splits the string using given regex expression and returns array of string.
    • split(String regex, int limit): This method splits the string using given regex expression and return array of string but the element of array is limited by the specified limit. If the specified limit is 2 then the method return an array of size 2.
    package com.journaldev.examples;
    
    /**
     * Java String split example
     * 
     * @author pankaj
     *
     */
    public class StringSplitExample {
    
    	public static void main(String[] args) {
    		
    		String s = "a/b/c/d";
    		String[] a1 = s.split("/");
    		System.out.println("split string using only regex:");
    		for (String string : a1) {
    			System.out.println(string);
    		}
    		System.out.println("split string using regex with limit:");
    		String[] a2 = s.split("/", 2);
    		for (String string : a2) {
    			System.out.println(string);
    		}
    	}
    
    }

    Output of above program is:

    Java String split()方法用于使用给定的表达式拆分字符串。 split()方法有两种变体。

    • split(String regex) :此方法使用给定的regex表达式拆分字符串并返回字符串数组。
    • split(String regex, int limit) :此方法使用给定的regex表达式拆分字符串并返回string数组,但array的元素受指定的限制。 如果指定的限制为2,则该方法返回大小为2的数组。
    package com.journaldev.examples;
    
    /**
     * Java String split example
     * 
     * @author pankaj
     *
     */
    public class StringSplitExample {
    
    	public static void main(String[] args) {
    		
    		String s = "a/b/c/d";
    		String[] a1 = s.split("/");
    		System.out.println("split string using only regex:");
    		for (String string : a1) {
    			System.out.println(string);
    		}
    		System.out.println("split string using regex with limit:");
    		String[] a2 = s.split("/", 2);
    		for (String string : a2) {
    			System.out.println(string);
    		}
    	}
    
    }

    上面程序的输出是:

  2. contains(CharSequence s) (contains(CharSequence s))

    Java String contains() methods checks if string contains specified sequence of character or not. This method returns true if string contains specified sequence of character, else returns false.

    package com.journaldev.examples;
    
    /**
     * Java String contains() Example
     * 
     * @author pankaj
     *
     */
    public class StringContainsExample {
    
    	public static void main(String[] args) {
    		String s = "Hello World";
    		
    		System.out.println(s.contains("W"));//true
    		System.out.println(s.contains("X"));//false
    	}
    
    }

    Output of above program is:

    Java String contains()方法检查字符串是否包含指定的字符序列。 如果string包含指定的字符序列,则此方法返回true,否则返回false。

    package com.journaldev.examples;
    
    /**
     * Java String contains() Example
     * 
     * @author pankaj
     *
     */
    public class StringContainsExample {
    
    	public static void main(String[] args) {
    		String s = "Hello World";
    		
    		System.out.println(s.contains("W"));//true
    		System.out.println(s.contains("X"));//false
    	}
    
    }

    上面程序的输出是:

  3. 长度() (length())

    Java String length() method returns the length of string.

    package com.journaldev.examples;
    
    /**
     * Java String length
     * 
     * @author pankaj
     *
     */
    public class StringLengthExample {
    
    	public static void main(String[] args) {
    		
    		String s1 = "abc";
    		String s2 = "abcdef";
    		String s3 = "abcdefghi";
    		
    		System.out.println(s1.length());//3
    		System.out.println(s2.length());//6
    		System.out.println(s3.length());//9
    
    	}
    
    }

    Java String length()方法返回字符串的长度。

  4. 更换() (replace())

    Java String replace() method is used to replace a specific part of string with other string. There are four variants of replace() method.

    • replace(char oldChar, char newChar): This method replace all the occurrence of oldChar with newChar in string.
    • replace(CharSequence target, CharSequence replacement): This method replace each target literals with replacement literals in string.
    • replaceAll(String regex, String replacement): This method replace all the occurrence of substring matches with specified regex with specified replacement in string.
    • replaceFirst(String regex, String replacement): This method replace first occurrence of substring that matches with specified regex with specified replacement in string.
    package com.journaldev.examples;
    
    /**
     * Java String replace
     * 
     * @author pankaj
     *
     */
    public class StringReplaceExample {
    
    	public static void main(String[] args) {
    		
    		//replace(char oldChar,  char newChar)
    		String s = "Hello World";
    		s = s.replace('l', 'm');
    		System.out.println("After Replacing l with m :");
    		System.out.println(s);
    		
    		//replaceAll(String regex, String replacement)
    		String s1 = "Hello journaldev, Hello pankaj";
    		s1 = s1.replaceAll("Hello", "Hi");
    		System.out.println("After Replacing :");
    		System.out.println(s1);
    		
    		//replaceFirst(String regex, String replacement) 
    		String s2 = "Hello guys, Hello world";
    		s2 = s2.replaceFirst("Hello", "Hi");
    		System.out.println("After Replacing :");
    		System.out.println(s2);
    
    	}
    
    }

    The output of above program is:

    Java String replace()方法用于将字符串的特定部分替换为其他字符串。 replace()方法有四个变体。

    • replace(char oldChar, char newChar) :此方法用字符串中的newChar替换所有出现的oldChar。
    • replace(CharSequence target, CharSequence replacement) :此方法用字符串中的替换文字替换每个目标文字。
    • replaceAll(String regex, String replacement) :此方法使用指定的regex替换所有出现的与指定regex匹配的子字符串。
    • replaceFirst(String regex, String replacement) :此方法用字符串中的指定替换替换第一次出现的与指定regex匹配的子字符串。
    package com.journaldev.examples;
    
    /**
     * Java String replace
     * 
     * @author pankaj
     *
     */
    public class StringReplaceExample {
    
    	public static void main(String[] args) {
    		
    		//replace(char oldChar,  char newChar)
    		String s = "Hello World";
    		s = s.replace('l', 'm');
    		System.out.println("After Replacing l with m :");
    		System.out.println(s);
    		
    		//replaceAll(String regex, String replacement)
    		String s1 = "Hello journaldev, Hello pankaj";
    		s1 = s1.replaceAll("Hello", "Hi");
    		System.out.println("After Replacing :");
    		System.out.println(s1);
    		
    		//replaceFirst(String regex, String replacement) 
    		String s2 = "Hello guys, Hello world";
    		s2 = s2.replaceFirst("Hello", "Hi");
    		System.out.println("After Replacing :");
    		System.out.println(s2);
    
    	}
    
    }

    上面程序的输出是:

  5. 格式() (format())

    Java Sting format() method is used to format the string. There is two variants of java String format() method.

    • format(Locale l, String format, Object… args): This method formats the string using specified locale, string format and arguments.
    • format(String format, Object… args): This method formats the string using specified string format and arguments.
    package com.journaldev.examples;
    
    import java.util.Locale;
    
    /**
     * Java String format
     * 
     * @author pankaj
     *
     */
    public class StringFormatExample {
    
    	public static void main(String[] args) {
    		
    		String s = "journaldev.com";
    		// %s is used to append the string
    		System.out.println(String.format("This is %s", s));
    		
    		//using locale as Locale.US
    		System.out.println(String.format(Locale.US, "%f", 3.14));
    	}
    }

    Output of above program is:

    Java Sting format()方法用于格式化字符串。 java String format()方法有两种变体。

    • format(Locale l, String format, Object… args) :此方法使用指定的语言环境,字符串格式和参数来格式化字符串。
    • format(String format, Object… args) :此方法使用指定的字符串格式和参数格式化字符串。
    package com.journaldev.examples;
    
    import java.util.Locale;
    
    /**
     * Java String format
     * 
     * @author pankaj
     *
     */
    public class StringFormatExample {
    
    	public static void main(String[] args) {
    		
    		String s = "journaldev.com";
    		// %s is used to append the string
    		System.out.println(String.format("This is %s", s));
    		
    		//using locale as Locale.US
    		System.out.println(String.format(Locale.US, "%f", 3.14));
    	}
    }

    上面程序的输出是:

  6. substring() (substring())

    This method returns a part of the string based on specified indexes.

    package com.journaldev.examples;
    
    /**
     * Java String substring
     *
     */
    public class StringSubStringExample {
    
    	public static void main(String[] args) {
    		
    		String s = "This is journaldev.com";
    		s = s.substring(8,18);
    		System.out.println(s);
    	}
    }

    此方法根据指定的索引返回字符串的一部分。

字符串串联 (String Concatenation)

String concatenation is very basic operation in java. String can be concatenated by using “+” operator or by using concat() method.

字符串连接是Java中非常基本的操作。 可以使用“ +”运算符或使用concat()方法来连接字符串。

package com.journaldev.examples;

/**
 * Java String concatenation
 * 
 * @author pankaj
 *
 */
public class StringConcatExample {

	public static void main(String[] args) {
		
		String s1 = "Hello";
		String s2 = "World";
		String s3 = s1 + s2;
		//using + operator
		System.out.println("Using + operator: ");
		System.out.println(s3);
		
		//using concat method
		System.out.println("Using concat method: ");
		System.out.println(s1.concat(s2));

	}

}

Output of above program is:

上面程序的输出是:

Using + operator: 
HelloWorld
Using concat method: 
HelloWorld

Check this post for more information about String Concatenation in Java.

检查此文章以获取有关Java中的字符串连接的更多信息。

Java字符串池 (Java String Pool)

Memory management is the most important aspect of any programming language. Memory management in case of string in Java is a little bit different than any other class. To make Java more memory efficient, JVM introduced a special memory area for the string called String Constant Pool.

内存管理是任何编程语言中最重要的方面。 Java中使用字符串的情况下的内存管理与任何其他类都有些不同。 为了使Java的内存使用效率更高,JVM为字符串引入了一个特殊的存储区域,称为字符串常量池。

When we create a string literal it checks if there is identical string already exist in string pool or not. If it is there then it will return the reference of the existing string of string pool.

当我们创建字符串文字时,它会检查字符串池中是否已经存在相同的字符串。 如果存在,它将返回字符串池现有字符串的引用。

Let’s have a look at the below example program.

让我们看一下下面的示例程序。

package com.journaldev.examples;

/**
 * Java String Pool Example
 * 
 */
public class StringPoolExample {

	public static void main(String[] args) {
		
		String a = "abc";
		String b = "abc";
		String c = "def";
		
		//same reference
		if (a==b) {
			System.out.println("Both string refer to the same object");
		}
		
		//different reference
		if (a==c) {
			System.out.println("Both strings refer to the same object");
		}else {
			System.out.println("Both strings refer to the different object");
		}

	}

}

The output of above program is:

上面程序的输出是:

Both string refer to the same object
Both strings refer to the different object

Check this post for more about Java String Pool.

查看此文章以获取有关Java String Pool的更多信息。

字符串intern()方法 (String intern() Method)

When we create a string using string literal, it will be created in string pool but what if we create a string using new keyword with the same value that exists in string pool? Can we move the String from heap memory to string pool?

当我们使用字符串文字创建字符串时,将在字符串池中创建该字符串,但是如果我们使用与字符串池中存在的相同值的new关键字创建一个字符串怎么办? 我们可以将String从堆内存移到字符串池吗?

For this intern() method is used and it returns a canonical representation of string object. When we call intern() method on string object that is created using the new keyword, it checks if there is already a String with the same value in the pool?

为此使用了intern()方法,它返回字符串对象的规范表示形式。 当我们对使用new关键字创建的字符串对象调用intern()方法时,它将检查池中是否已经存在具有相同值的String?

If yes, then it returns the reference of that String object from the pool. If not, then it creates a new String with the same content in the pool and returns the reference.

如果是,则它从池中返回该String对象的引用。 如果不是,那么它将在池中创建一个具有相同内容的新String并返回引用。

package com.journaldev.examples;

/**
 * Java String intern
 * 
 * @author pankaj
 *
 */
public class StringInternExample {

	public static void main(String[] args) {
		
		String s1 = "pankaj";
		String s2 = "pankaj";
		String s3 = new String("pankaj");
		
		System.out.println(s1==s2);//true
		System.out.println(s2==s3);//false
		
		String s4 = s3.intern();
		System.out.println(s1==s4);//true

	}

}

Check this post to learn more about Java String intern method.

检查这篇文章,以了解有关Java String intern方法的更多信息。

字符串不变性的好处 (String Immutability Benefits)

Some of the benefits of String being immutable class are:

String是不可变类的一些好处是:

  1. String Constant Pool, hence saves memory.

    字符串常量池,因此节省了内存。
  2. Security as it’s can’t be changed.

    安全性无法更改。
  3. Thread safe

    线程安全
  4. Class Loading security

    类加载安全

Check this post for more about Sting Immutablity Benefits.

查看此帖子,了解更多有关St刺免疫好处的信息

Java 8字符串join() (Java 8 String join())

A new static method join() has been added in String class in Java 8. This method returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter. Let’s look at an example to understand it easily.

Java 8的String类中添加了一个新的静态方法join()。此方法返回一个新的String,该字符串由CharSequence元素的副本与指定定界符的副本组成。 让我们看一个示例以轻松理解它。

List<String> words = Arrays.asList(new String[]{"Hello", "World", "2019"});
String msg = String.join(" ", words);
System.out.println(msg);

Output: Hello World 2019

输出: Hello World 2019

Java 9字符串方法 (Java 9 String Methods)

There are two methods added in String class in Java 9 release. They are – codePoints() and chars(). Both of these methods return IntStream object on which we can perform some operations.

Java 9发行版的String类中添加了两个方法。 它们是– codePoints()和chars()。 这两个方法都返回IntStream对象,我们可以在该对象上执行一些操作。

Let’s have a quick look at these methods.

让我们快速看一下这些方法。

String s = "abc";

s.codePoints().forEach(x -> System.out.println(x));

s.chars().forEach(x -> System.out.println(x));

Output:

输出:

97
98
99
97
98
99

Java 11字符串类新方法 (Java 11 String Class New Methods)

There are many new methods added in String class in Java 11 release.

Java 11发行版的String类中添加了许多新方法。

  • isBlank() – returns true if the string is empty or contains only white space codepoints, otherwise false.

    isBlank()–如果字符串为空或仅包含空格代码点,则返回true,否则返回false。
  • lines() – returns a stream of lines extracted from this string, separated by line terminators.

    lines()–返回从此字符串中提取的行流,以行终止符分隔。
  • strip(), stripLeading(), stripTrailing() – for stripping leading and trailing white spaces from the string.

    strip(),stripLeading(),stripTrailing()–用于从字符串中删除开头和结尾的空格。
  • repeat() – returns a string whose value is the concatenation of this string repeated given number of times.

    repeat()–返回一个字符串,该字符串的值是重复给定次数的此字符串的串联。

Let’s look at an example program for these methods.

让我们看一下这些方法的示例程序。

package com.journaldev.strings;

import java.util.List;
import java.util.stream.Collectors;

/**
 * JDK 11 New Functions in String class
 * 
 * @author pankaj
 *
 */
public class JDK11StringFunctions {

	public static void main(String[] args) {
		// isBlank()
		String s = "abc";
		System.out.println(s.isBlank());
		s = "";
		System.out.println(s.isBlank());

		// lines()
		String s1 = "Hi\nHello\rHowdy";
		System.out.println(s1);
		List lines = s1.lines().collect(Collectors.toList());
		System.out.println(lines);

		// strip(), stripLeading(), stripTrailing()
		String s2 = "  Java,  \tPython\t ";
		System.out.println("#" + s2 + "#");
		System.out.println("#" + s2.strip() + "#");
		System.out.println("#" + s2.stripLeading() + "#");
		System.out.println("#" + s2.stripTrailing() + "#");

		// repeat()
		String s3 = "Hello\n";
		System.out.println(s3.repeat(3));
		s3 = "Co";
		System.out.println(s3.repeat(2));

	}

}

Output:

输出:

false
true
Hi
Hello
Howdy
[Hi, Hello, Howdy]
#  Java,  	Python	 #
#Java,  	Python#
#Java,  	Python	 #
#  Java,  	Python#
Hello
Hello
Hello

CoCo

That’s all about Java String class, it’s method and String manipulation examples.

这就是有关Java String类的全部内容,它是方法和String操作示例。

GitHub Repository. GitHub存储库中签出更多String示例。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/16928/java-string

java字符串

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324090971&siteId=291194637