Share an example tutorial of String class in Java
String: String type, here I will share with you an example tutorial of the String class in Java
1. Constructor
String(byte[] bytes): By byte Array constructor string object.
String(char[ ] value): Construct a string object through a char array.
String(Sting original): Construct a copy of original. That is: copy an original.
String(StringBuffer buffer): Construct a string object through the StringBuffer array.
For example:
byte[] b = {'a','b','c','d','e','f','g','h','i','j'}; char[] c = {'0','1','2','3','4','5','6','7','8','9'}; String sb = new String(b); //abcdefghij String sb_sub = new String(b,3,2); //de String sc = new String(c); //0123456789 String sc_sub = new String(c,3,2); //34 String sb_copy = new String(sb); //abcdefghij System.out.println("sb:"+sb); System.out.println("sb_sub:"+sb_sub); System.out.println("sc:"+sc); System.out.println("sc_sub:"+sc_sub); System.out.println("sb_copy:"+sb_copy);
Output result: sb:abcdefghij
sb_sub:de
sc_sub:34
sb_copy:abcdefghij
②, writing format: [Decomposition] & lt; return type & gt; & lt; method name ([parameter list]) & gt;
## For example: static into The method (parseInt) is a class method (static), the return type is (int), and the method requires a String type.
1. char charAt(int index): Get a certain character in the string, where the parameter index refers to the ordinal number in the string. The ordinal number of the string starts from 0 and goes to length()-1.
For example:
String s = new String("abcdefghijklmnopqrstuvwxyz"); System.out.println("s.charAt(5): " + s.charAt(5) );
The result is: s.charAt(5): f
2. int compareTo(String anotherString): Compare the current String object with anotherString. The equality relationship returns 0; when they are not equal, the comparison starts from the 0th character of the two strings and returns the first unequal character difference. In another case, the front part of the longer string happens to be the shorter string. , return their length difference.
Object
o): If o is a String object, it has the same function as 2; otherwise, a ClassCastException is thrown.
For example: String s1 = new String("abcdefghijklmn");
String s2 = new String("abcdefghij");
String s3 = new String("abcdefghijalmn");
System.out.println("s1.compareTo(s2): " + s1.compareTo(s2) ); //返回长度差
System.out.println("s1.compareTo(s3): " + s1.compareTo(s3) ); //返回'k'-'a'的差
s1.compareTo(s3): 10
5. boolean contentEquals(StringBuffer sb): Compare the String object with the StringBuffer object sb.
6. static String copyValueOf(char[] data):
7. static String copyValueOf(char[] data, int offset, int count): These two methods convert the char array into String and match one of them The constructor is similar.
8. boolean endsWith(String suffix): Whether the String object ends with suffix.
For example:
String s1 = new String("abcdefghij"); String s2 = new String("ghij"); System.out.println("s1.endsWith(s2): " + s1.endsWith(s2) );
The result is: s1.endsWith(s2): true
9. boolean equals(Object anObject): When anObject is not empty and is the same as the current String object, return true; Otherwise, return false. 10. byte[] getBytes(): Convert the String object into a byte array.
11. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): This method copies the string to the character array. Among them, srcBegin is the starting position of the copy, srcEnd is the end position of the copy, the string value dst is the target character array, and dstBegin is the copy starting position of the target character array.
For example:
char[] s1 = {'I',' ','l','o','v','e',' ','h','e','r','!'};//s1=I love her! String s2 = new String("you!"); s2.getChars(0,3,s1,7); //s1=I love you! System.out.println( s1 );
The result is: I love you!
12. int hashCode(): Returns the hash code of the current character. 13. int indexOf(int ch): Only find the first matching character position.
14. int indexOf(int ch, int fromIndex): Find the first matching character position starting from fromIndex.
15. int indexOf(String str): Only find the first matching string position.
16. int indexOf(String str, int fromIndex): Find the first matching string position starting from fromIndex.
For example:
String s = new String("write once, run anywhere!"); String ss = new String("run"); System.out.println("s.indexOf('r'): " + s.indexOf('r') ); System.out.println("s.indexOf('r',2): " + s.indexOf('r',2) ); System.out.println("s.indexOf(ss): " + s.indexOf(ss) );
结果为:s.indexOf('r'): 1
s.indexOf('r',2): 12
s.indexOf(ss): 12
17. int lastIndexOf(int ch)
18. int lastIndexOf(int ch, int fromIndex)
19. int lastIndexOf(String str)
20. int lastIndexOf(String str, int fromIndex) 以上四个方法与13、14、15、16类似,不同的是:找最后一个匹配的内容。
public class CompareToDemo { public static void main (String[] args) { String s1 = new String("acbdebfg"); System.out.println(s1.lastIndexOf((int)'b',7)); } }
运行结果:5
(其中fromIndex的参数为 7,是从字符串acbdebfg的最后一个字符g开始往前数的位数。既是从字符c开始匹配,寻找最后一个匹配b的位置。所以结果为 5)
21. int length() :返回当前字符串长度。
22. String replace(char oldChar, char newChar) :将字符号串中第一个oldChar替换成newChar。
23. boolean startsWith(String prefix) :该String对象是否以prefix开始。
24. boolean startsWith(String prefix, int toffset) :该String对象从toffset位置算起,是否以prefix开始。
例如:
String s = new String("write once, run anywhere!"); String ss = new String("write"); String sss = new String("once"); System.out.println("s.startsWith(ss): " + s.startsWith(ss) ); System.out.println("s.startsWith(sss,6): " + s.startsWith(sss,6) );
结果为:s.startsWith(ss): true
s.startsWith(sss,6): true
25. String substring(int beginIndex) :取从beginIndex位置开始到结束的子字符串。
26.String substring(int beginIndex, int endIndex) :取从beginIndex位置开始到endIndex位置的子字符串。
27. char[ ] toCharArray() :将该String对象转换成char数组。
28. String toLowerCase() :将字符串转换成小写。
29. String toUpperCase() :将字符串转换成大写。
例如:
String s = new String("java.lang.Class String"); System.out.println("s.toUpperCase(): " + s.toUpperCase() ); System.out.println("s.toLowerCase(): " + s.toLowerCase() );
结果为:s.toUpperCase(): JAVA.LANG.CLASS STRING
s.toLowerCase(): java.lang.class string
30. static String valueOf(boolean b)
31. static String valueOf(char c)
32. static String valueOf(char[] data)
33. static String valueOf(char[] data, int offset, int count)
34. static String valueOf(double d)
35. static String valueOf(float f)
36. static String valueOf(int i)
37. static String valueOf(long l)
38. static String valueOf(Object obj)
以上方法用于将各种不同类型转换成Java字符型。这些都是类方法。
Java中String类的常用方法:
public char charAt(int index) 返回字符串中第index个字符; public int length() 返回字符串的长度; public int indexOf(String str) 返回字符串中第一次出现str的位置; public int indexOf(String str,int fromIndex) 返回字符串从fromIndex开始第一次出现str的位置; public boolean equalsIgnoreCase(String another) 比较字符串与another是否一样(忽略大小写); public String replace(char oldchar,char newChar) 在字符串中用newChar字符替换oldChar字符 public boolean startsWith(String prefix) 判断字符串是否以prefix字符串开头; public boolean endsWith(String suffix) 判断一个字符串是否以suffix字符串结尾; public String toUpperCase() 返回一个字符串为该字符串的大写形式; public String toLowerCase() 返回一个字符串为该字符串的小写形式 public String substring(int beginIndex) 返回该字符串从beginIndex开始到结尾的子字符串; public String substring(int beginIndex,int endIndex) 返回该字符串从beginIndex开始到endsIndex结尾的子字符串 public String trim() 返回该字符串去掉开头和结尾空格后的字符串 public String[] split(String regex) 将一个字符串按照指定的分隔符分隔,返回分隔后的字符串数组
实例:
public class SplitDemo{ public static void main (String[] args) { String date = "2008/09/10"; String[ ] dateAfterSplit= new String[3]; dateAfterSplit=date.split("/"); //以“/”作为分隔符来分割date字符串,并把结果放入3个字符串中。 for(int i=0;i<dateAfterSplit.length;i++) System.out.print(dateAfterSplit[i]+" "); } }
运行结果:2008 09 10 //结果为分割后的3个字符串
实例:
TestString1.java:程序代码public class TestString1{ public static void main(String args[]) { String s1 = "Hello World" ; String s2 = "hello world" ; System.out.println(s1.charAt(1)) ; System.out.println(s2.length()) ; System.out.println(s1.indexOf("World")) ; System.out.println(s2.indexOf("World")) ; System.out.println(s1.equals(s2)) ; System.out.println(s1.equalsIgnoreCase(s2)) ; String s = "我是J2EE程序员" ; String sr = s.replace('我','你') ; System.out.println(sr) ; }} TestString2.java:
程序代码
public class TestString2 { public static void main(String args[]) { String s = "Welcome to Java World!" ; String s2 = " magci " ; System.out.println(s.startsWith("Welcome")) ; System.out.println(s.endsWith("World")) ; String sL = s.toLowerCase() ; String sU = s.toUpperCase() ; System.out.println(sL) ; System.out.println(sU) ; String subS = s.substring(11) ; System.out.println(subS) ; String s1NoSp = s2.trim() ; System.out.println(s1NoSp) ; }
【相关推荐】
1. java中String是对象还是类?详解java中的String
3. Java中String类的常用方法是什么?总结Java中String类的常用方法
The above is the detailed content of Share an example tutorial of String class in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
