Learn how toget thefirst 4 characters of a String or simply any number of the first characters of a string in Java. 1. Using Plain Java To get a substring having the first 4 chars first check the length of the string. If the string length is greater than 4 then usesubstring(int begi...
s1 = s1.substring(x,y) + ""; 1. JDK 7 中的substring 上述问题在JDK 7中得到了解决。JDK 7中,substring方法会在堆中创建一个新的数组。 源码 //JDK 7 /** * Allocates a new {@code String} that contains characters from a subarray * of the character array argument. The {@code offset} ...
publicclassMain{publicstaticvoidmain(String[]args){Stringstr="Hello, World!";// 截取第一个字符StringfirstChar=str.substring(0,1);System.out.println("第一个字符是:"+firstChar);// 截取最后一个字符StringlastChar=str.substring(str.length()-1,str.length());System.out.println("最后一个字符是...
JDK 7中,substring方法会在堆中创建一个新的数组。 源码 //JDK 7 /** * Allocates a new {@codeString} that contains characters from a subarray * of the character array argument. The {@codeoffset} argument is the * index of the first character of the subarray and the {@codecount} * arg...
Java中的substring函数是我们经常使用的一个函数,用来截取当前字符串的子串,定义如下: publicfinalclassString{publicString substring(intbeginIndex);publicString substring(intbeginIndex,intendIndex); } 使用及声明都非常简单,但是你了解其中的细节吗? 我们再看一下substring的实现: ...
类在这点中做得很好。在 String 类中许多会对字符串进行操作的方法中,例如replaceAll()或者substring(...
We may need to get the last 4 characters when we are dealing with customer-sensitive data such as phone numbers or SSNs. In this case, we need to display only the last 4 characters to mask the sensitive data. To get a substring having the last 4 chars first check the length of the...
Splits the specified String containing the specified substring into individual Strings that were delimited by the specified substring. static java.util.Vectortokenizer(java.lang.String pSrc, java.lang.String pToken) Returns a Vector of the tokenized source. ...
Here is an example, that gets the first 3 characters of a string: String str = "google"; System.out.println(str.substring(0, 3)); Output: "goo" Note: The extraction starts at index 0 and ends before index 3. Similarly, we can also get the first 4 characters of a string like thi...
“A substring is a contiguous sequence of characters within a string. For instance, “the best of” is a substring of “It was the best of times”. Java substring() method returns a ‘substring’ of the specified string. The creation of the ‘substring’ depends on the parameter passed ...