一 String

1.1 == 和 equal()

        System.out.println("-------两个内容相同,创建方式不同的字符串,面试题--------");
String s3 = "abc";
String s4 = new String("abc"); //s3和s4有什么不同呢?
/*
* s3创建,在内存中只有一个对象。
*
* s4创建,在内存中有两个对象。
*/ System.out.println(s3==s4);//false
// 因为String复写了equals方法,
// 建立字符串自己的判断相同的依据。通过字符串对象中的内容来判断的。
System.out.println(s3.equals(s4));//true,

1.2 常见方法及查找的方法

1,字符串是一个对象,那么它的方法必然时围绕操作这个对象的数据而定义的。
2,你认为字符串中有哪些功能呢?
  2.1 有多少个字符?
  int length()

  2.2 字符的位置。
   int indexOf(ch,fromIndex);

  2.3 获取指定位置上的字符。
   char charAt(int)

   2.4 获取部分字符串。
  String substring(int start,int end);

String str = "abada";
// System.out.println("length="+str.length());
int len = str.length();
System.out.println("len="+len); //------a字母出现的位置------
int index = str.indexOf('a');//获取的是a字符第一次出现的位置。
System.out.println("index="+index);
//------第二个a字母出现的位置------ int index1 = str.indexOf('a',index+);
System.out.println("index1="+index1);
//------第三个a字母出现的位置------
int index2 = str.indexOf('a',index1+);
System.out.println("index2="+index2); str = "sdfghjkl;wertyuiop[sdfghjkla;";
int index3 = str.lastIndexOf('m');//如果要找的字符不存在,-1
System.out.println("index3="+index3); //----------获取指定位置上字符。---------------
str = "itcast";
char ch = str.charAt();//不存在角标会发生StringIndexOutOfBoundsException
System.out.println("ch="+ch); //------------获取部分字符串----------------------
String s = str.substring(, );//包含头,不包含尾。
System.out.println("s="+s);

1.3 String 练习

* String方法查找练习。
* 1,字符串是否以指定字符串开头。结尾同理。
* boolean startsWith(string)
* boolean endsWith(string)
*
* 2,字符串中是否包含另一个字符串。
* boolean contains(string);
* int indexOf(string)//如果返回-1,表示不存在。
*
* 3,字符串中另一个字符串出现的位置。
* int indexOf(string)
* 4,将字符串中指定的字符串替换成另一个字符串
* String replace(oldstring , newstring)
*
* 5,字符串如何比较大小?@
*
* 6,将字符串转成一个字符数组。或者字节数组。
* toCharArray()
* getBytes()
* 7,将字母字符串转成大写的字母字符串。
* toUpperCase()
* toLowerCase();
* 8,将字符串按照指定的方式分解成多个字符串, "lisi,wangwu,zhaoliu"获取三个姓名。
* String[] split(string);

//
String str = "StringDemo.java";
boolean b1 = str.startsWith("Demo");//false
//
boolean b2 = str.contains("Demo");//CharSequence x = "Demo";//true
//
String s = str.replace("haha", "Test");//没有被替换内容时,结果是原串儿。
System.out.println("s="+s);
//
char[] chs = str.toCharArray();
byte[] bytes = str.getBytes();
//
String upperString = str.toUpperCase(); //
str = "lisi,wangwu,zhaoliu";
String[] names = str.split(",");
for (int i = ; i < names.length; i++) {
System.out.println(names[i]);
} //5,字符串如何比较大小?
int result = "ab".compareTo("ab");//只要想让对象具备比较大小的功能只需实现Comparable接口。
System.out.println("result:"+result);

1.4 comparable

package test;

class Person implements Comparable {
private String name ;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
} public int compareTo(Object o) {
if(!(o instanceof Person))
throw new RuntimeException("o");
Person p = (Person)o;
return this.age - p.age;
} }

1.5 练习

1 字符串数组排序

/**
* 字符串数组
* 思路:
* 1,曾经玩过int[]排序,选择,冒泡。
* 2,字符串排序同理。
* 3,for嵌套循环。
* 4,循环中进行元素的大小比较,满足条件位置置换。
* @param strs
*/

    public static void sortString(String[] strs) {

        for (int i = ; i < strs.length - ; i++) {
for (int j = i + ; j < strs.length; j++) {
if(strs[i].compareTo(strs[j])>){//对象比较用方法。compareTo。
swap(strs,i,j);
}
}
}
// Arrays.sort(strs); }
/*
* 数组元素位置置换。
*/
private static void swap(String[] strs, int i, int j) {
String temp = strs[i];
strs[i] = strs[j];
strs[j] = temp; }

2 字符串出现的次数

/*
*
* 案例二:
* "witcasteritcasttyuiitcastodfghjitcast"有几个itcast
*
* 思路:
* 1,无非就是在一个字符串中查找另一个字符串。indexOf。
* 2,查找到第一次出现的指定字符串后,如何查找第二个呢?
* 3,无需在从头开始,只要从第一次出现的位置+要找的字符串的长度的位置开始向后查找下一个第一次出现的位置即可。
* 4,当返回的位置是-1时,查找结束。
*/

String str = "witcasteritcasttyuiitcastodfghjitcast";
String key = "itcast"; int count = getKeyCount(str,key);
System.out.println("count="+count); /**
* 获取key在str中出现次数。
* @param str
* @param key
* @return
*/
public static int getKeyCount(String str, String key) { //1,定义变量。记录每一次找到的key的位置。
int index = ;
//2,定义变量,记录出现的次数。
int count = ; //3,定义循环。只要索引到的位置不是-1,继续查找。
while((index = str.indexOf(key,index))!=-){ //每循环一次,就要明确下一次查找的起始位置。
index = index + key.length(); //每查找一次,count自增。
count++;
}
return count;
}

3 按照长度递减获取字符串

* 案例三: "itcast_sh"要求,将该字符串按照长度由长到短打印出来。 itcast_sh itcast_s tcast_sh
*/

String str = "itcast";
printStringByLength(str); } public static void printStringByLength(String str) { // 1,通过分析,发现是for嵌套循环。
for (int i = ; i < str.length(); i++) { for (int start = , end = str.length() - i; end <= str.length(); start++, end++) { //根据start,end截取字符串。
String temp = str.substring(start, end);
System.out.println(temp);
} } }

二 StringBuffer

2.1 使用

/*
* StringBuffer:
* 1,是一个字符串缓冲区,其实就是一个容器。
* 2,长度是可变任意类型都行。注意:是将任意数据都转成字符串进行存储
* 3,容器对象提供很多对容器中数据的操作功能,比如:添加,删除,查找,修改
* 4,必须所有的数据最终变成一个字符串。
* 和数组最大的不同就是:数组存储完可以单独操作每一个元素,每一个元素都是独立的。
* 字符串缓冲区,所有存储的元素都被转成字符串,而且最后拼成了一个大的字符串。
*
* 可变长度数组的原理:新建数组,并复制数组元素到新数组中。
*/

//1,创建一个字符串缓冲区对象。用于存储数据。
StringBuffer sb = new StringBuffer(); //2,添加数据。不断的添加数据后,要对缓冲区的最后的数据进行操作,必须转成字符串才可以。
String str = sb.append(true).append("hehe").toString();
// sb.append("haha"); // sb.insert(2, "it");//插入 // sb.delete(1, 4);//删除 // sb.replace(1, 4, "cast");
// sb.setLength(2);
System.out.println(sb); // String s = "a"+5+'c';//原理就是以下这句
// s = new StringBuffer().append("a").append(5).append('c').toString();

2.2 练习

package cn.itcast.api.stringbuffer;

public class StringBufferTest {

    /**
* @param args
*/
public static void main(String[] args) { /*
* int[] arr = {34,12,89,68};
* 将一个int[]中元素转成字符串 格式 [34,12,89,68]
*/
int[] arr = {,,,};
String str = toString_2(arr);
System.out.println(str);
} /**
* 缓冲区的应用:无论多少数据,什么类型都不重要,只要最终变成字符串就可以StringBuffer这个容器。
* @param arr
* @return
*/
public static String toString_2(int[] arr) {
//1,创建缓冲区。
StringBuffer sb = new StringBuffer(); sb.append("[");
for (int i = ; i < arr.length; i++) {
if(i!=arr.length-){
sb.append(arr[i]+",");
}else{
sb.append(arr[i]+"]");
}
} return sb.toString();
} public static String toString(int[] arr) { //用字符串连接。
String str = "[";
for (int i = ; i < arr.length; i++) {
if(i!=arr.length-){
str+=arr[i]+",";
}else{
str+=arr[i]+"]";
}
}
return str;
} }

2.3 Stringbuilder 和Stringbuffer区别

package cn.itcast.api.stringbuffer;

public class StringBuilderDemo {

    /**
* @param args
*/
public static void main(String[] args) { /*
* StringBuilder和StringBuffer的区别。
* StringBuilder:非同步的。单线程访问效率高。
* StringBuffer:同步的,多线程访问安全。
*
*/ }
}
/*
synchronized append(); synchronized delete(); synchronized insert(); */

最新文章

  1. 本机,同机房,同城,异地,不同城,腾讯云ping延时值
  2. 【网站国际化必备】Asp.Net MVC 集成Paypal(贝宝)快速结账 支付接口 ,附源码demo
  3. bash的配置
  4. HTTP1.0与HTTP1.1的区别
  5. word-break:brea-all;word-wrap:break-word的区别
  6. 【wikioi】1230 元素查找(巨水题+set/hash)
  7. Java-Lambda
  8. ListView中item的最外层使用margin属性失效
  9. Objc基础学习记录5
  10. ECshop 二次开发模板教程4
  11. Android开发UI之控件-Android-PullToRefresh
  12. C++对象的销毁
  13. C#扩充类
  14. dubbo 分布式架构学习视频链接
  15. 为什么Java中的String类是不可变的?
  16. Suricata 之IPS模式
  17. Git与远程reposiory的相关命令
  18. android---EditText的多行输入框
  19. int __get_order(unsigned long size)
  20. Python Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat)

热门文章

  1. 2-sat——poj3678经典建图
  2. Zuul的过滤器
  3. python随机数(转载)
  4. Windows操作系统下创建进程的过程
  5. css3中 百分比宽度减去固定宽度的写法
  6. WebSocket实践
  7. spring retry 重试机制完整例子
  8. 《DSP using MATLAB》Problem 8.19
  9. Maven入门指南
  10. typeof 、Object.prototype.toString和 instanceof