一、前言
本文章主要講解數(shù)組的一些基本操作,讓我們寫(xiě)代碼更加方便,像我們?cè)趯W(xué)c語(yǔ)言的時(shí)候常常會(huì)自己造輪子,好多方法都需要我們自己去寫(xiě),但是java封裝了很多方法給我們使用,讓我們看看都有哪些方法吧。
二、數(shù)組操作
1.charAt操作
這個(gè)方法是根據(jù)下標(biāo)取出字符串中的單個(gè)字符,這里不是字符數(shù)組。比如我定義了一個(gè)hello的字符串,我想取出它每一個(gè)字符,因?yàn)椴皇菙?shù)組所以我們不能用數(shù)組取值的方法。
代碼如下:
public class test {
public static void main(String[] args) {
String a = "helloWorld";
for (int i = 0; i < a.length(); i++) {
System.out.print(a.charAt(i)+" ");
}
}
}
輸出:
2.getBytes操作
作用:字符串轉(zhuǎn)換成字節(jié)數(shù)組,比如a就轉(zhuǎn)換成了對(duì)應(yīng)的ascii碼97。
代碼如下:
public class test {
public static void main(String[] args) {
String s1 = "abc";
byte[] arr1 = s1.getBytes();
for (int i = 0; i < arr1.length; i++) {
System.out.print(arr1[i]+" ");
}
}
}
輸出:
3.toCharArray操作
作用:將字符串轉(zhuǎn)換成字符數(shù)組。
代碼如下:
public class test {
public static void main(String[] args) {
String s2 = "hello world";
char[] arr2 = s2.toCharArray();
for (int i = 0; i < arr2.length; i++) {
System.out.print(arr2[i]+" ");
}
}
}
輸出:
4.String.valueOf
作用:把任意類(lèi)型數(shù)據(jù)轉(zhuǎn)換成字符串
public class test {
public static void main(String[] args) {
char[] arr3 = {'a','b','d'};
String s3 = String.valueOf(arr3);
System.out.println(s3);
}
}
輸出:
5.substring,toUpperCase,toLowerCase,concat
substring:截取字符串
toUpperCase:字母變大寫(xiě)
toLowerCase:字母變小寫(xiě)
concat:字符串連接
可以采用鏈?zhǔn)骄幊?br> 示例:
public class test {
public static void main(String[] args) {
String s = "asdaFDJSLasdf";
String s2 = s.substring(0,1).toUpperCase().concat(s.substring(1).toLowerCase());
System.out.println(s2);
}
}
輸出:
6.indexOf
作用:返回子字符串在主字符串中第一次出現(xiàn)的索引
示例:查找小字符串在大字符串中出現(xiàn)的次數(shù)
代碼:
public class test {
public static void main(String[] args) {
String s1 = "qweretetest,pipvobixcvtest,asdfjzchello";
String s2 = "test";
int count = 0;
int index = 0;
while ((index = s1.indexOf(s2)) != -1){
//截取出第一次出現(xiàn)后的所有字符串
s1 = s1.substring(index+s2.length());
System.out.println(s1);
count++;
}
System.out.println(count);
}
}
不懂的小伙伴可以自行Debug一下就知道程序怎么運(yùn)行的了。
輸出:
7.Arrays使用
toString:數(shù)組轉(zhuǎn)字符串
sort:數(shù)組排序
binarySearch:二分查找,返回目標(biāo)值的索引
示例:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-413027.html
public class Demo22_arrays {
public static void main(String[] args){
int[] arr = {33,11,55,66,22,44,88};
System.out.println(Arrays.toString(arr)); //數(shù)組轉(zhuǎn)字符串
Arrays.sort(arr); //排序
System.out.println(Arrays.toString(arr));
int[] arr2 = {1,2,3,4,5};
System.out.println(Arrays.binarySearch(arr2,2)); //查找字符串
}
}
輸出:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-413027.html
到了這里,關(guān)于java 數(shù)組和字符串操作的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!