最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
java中取字符串的第一个和最后一个字符
时间:2016-02-25 编辑:简简单单 来源:一聚教程网
java中,我们可以使用charAt()方法获取字符串的第一个和最后一个字符。该方法接收已给int型作为参数。
java.lang.String类中并定义这个方法,而是在java.lang.CharSequence接口中定义,因此,StringBuffer和StringBuilder类也可以使用这个方法。
代码实例:
public class Solution {
public static void main(String args[]) {
// You can use the charAt(int index) method to get the first and last
// character of a String in Java.
// suppose you want the first and last character from a String
// here first character of "iPhone"is "i" and last character
// is "e"
String phone = "iPhone";
char first = phone.charAt(0); // just like array, string index is zero based
char last = phone.charAt(phone.length() - 1); // last char is at index length - 1
System.out.printf("first character of string \"%s\" is '%c' %n", phone, first);
System.out.printf("last character of string \"%s\" is '%c' %n", phone, last);
// Alternatively, you can also get the character array from String
// and than extract first and last characters as shown below
String device = "Bluetooth headset";
char[] characters = device.toCharArray();
char firstChar = characters[0]; // first character is from index zero
char lastChar = characters[characters.length - 1]; // first character is from index length -1
System.out.printf("first character of string \"%s\" is '%c' %n",
device, firstChar);
System.out.printf("last character of string \"%s\" is '%c' %n",
device, lastChar);
// You can also use charAt() function to retrieve first and last
// character from StringBuffer and StringBuilder as well
StringBuffer buffer = new StringBuffer("Programming");
char firstCharacter = buffer.charAt(0);
char lastCharacter = buffer.charAt(1);
System.out.printf("first character of StringBuffer \"%s\" is '%c' %n",
buffer, firstCharacter);
System.out.printf("last character of StringBuffer \"%s\" is '%c' %n",
buffer, lastCharacter);
}
}
Output:
first character of string "iPhone" is 'i'
last character of string "iPhone" is 'e'
first character of string "Bluetooth headset" is 'B'
last character of string "Bluetooth headset" is 't'
first character of string "Programming" is 'P'
last character of string "Programming" is 'r'
第一种方式是先用toCharArray()方法将String转换为Char类型数组,然后获取第一个和最后一个字符。
第二种方式是直接使用charAt()方法获第一个和最后一个字符
length() - 1 是 最后一个字符的索引
不用正则.
str.substring(1,str.length-1);
相关文章
- java 打印一字符串,并在main()方法内调用它 04-21
- python字符串中的单双引 04-10
- 计算两个字符串最大公有子串 03-03
- 详解C语言中的字符串拼接(堆与栈) 01-15
- java字符串string,stringbuffer、stringbuilder详解 12-24
- python字符串的使用详解 09-22