JAVA笔记–字符串
由双引号("")包围的都是字符串。
声明:
String s = null;
创建字符串:
1、String(chat[] a);
char[] a = {‘c’, ‘h’, ‘i’, ‘n’, ‘a’};
String country = new String(a);
2、String(chat[] a, int offset, int length);
char[] a = {‘m’, ‘y’, ‘c’, ‘h’, ‘i’, ‘n’, ‘a’, ‘e’};
String country = new String(a, 2, 5);//2是index,5是提取的长度。
3、直接赋值
String country = “china”;
字符串的一些方法
1、连接字符串 +
String s1 = "I am ";
String s2 = “chinese”;
String s = s1 + s2;
备注:
只要"+"运算符的一个操作数是字符串,编译器就会将另一个操作数转换成字符串的形式。所以注意如下:
System.out.println(5 + 6 + " = " + 5 + 6);
输出结果:11 = 56
System.out.println(5 + 6 + " = " + (5 + 6));
输出结果:11 = 11
2、获取字符串长度(实际长度)
str.length();
3、字符或字符串查找
str.indexOf(substr)
str.lastIndexOf(substr)
4、获取指定位置的字符
str.charAt(int index)
5、获取子字符串
str.substring(int beginIndex)
str.substring(int beginIndex, int endIndex)
6、去除空格
str.trim()
备注:去掉始终的空格,不去掉中间的空格。
数组排序算法
1、冒泡排序
void sort(int[] arr)
{
int temp = 0;
for(int i = 1;i < arr.length;i++){
for(int j = 0;j < arr.length - i;j++){
if(arr[j] > arr[j + 1]){
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}