文章目录
- 一.String类
- 1.声明字符串
- 2.创建字符串
- 二.连接字符串
- 1.连接多个字符串
- 2.连接其他数据类型
- 三.获取字符串信息
- 1.获取字符串长度
- 2.字符串查找
- 3.获取指定索引位置的字符
一.String类
1.声明字符串
声明字符串可以用String。
例如 String s;
2.创建字符串
创建字符串有三种方法
第一种:
char a[]={'h','e','l','l','o'};
String s=new String(a);
//上面两句等价于:
String s=new String("hello");
第二种:
char a[]={'h','e','l','l','o'};
String s=new String(a,1,4);//第二个参数是截取位置,第三个是截取长度。
//上面两句等价于:
String s=new String("ello");
第三种:
String str1,str2;
str1="huagou";
str2="hello";
二.连接字符串
String s1=new String("hello");
String s2=new String("world");
String s=s1+""+s2;
1.连接多个字符串
String s1=new String("hello");
String s2=new String("world");
String s=s1+""+s2;
2.连接其他数据类型
int a=1;
float b=2.2f;
System.out.println("我每天花费"+a+"小时看java;"+b+"小时写博客");
三.获取字符串信息
1.获取字符串长度
String str="我是一名大一学生";
int size=str.length();
2.字符串查找
Strting提供了两种查找字符串的方法,即indexOf()与lastIndexOf()方法。
1. indexOf()方法返回的是搜索的字符或字符串首次出现的位置,
2. lastIndexOf()方法返回的是搜索的字符或字符串最后出现的位置。
(1)indlexOf语法如下:
String str ="we are students";
int size =str.indexOf("a");
//size的值为3。
(2) lastlndexOf(String)语法如下:
搜索的字符或字符串最后出现的位置,如果没有找到,则返回-1,如果参数是空字符串,则返回的值与调用str.length()返回值是一样的。
String str ="we are students";
int size =str.indexOf("e");
//size的值为11
String str ="we are students";
int size =str.indexOf("c");
//size的值为-1
String str ="we are students";
int size =str.indexOf("");
//size的值与str.length()返回的值一样。
3.获取指定索引位置的字符
String str="hello world";
char mych = str..charAt(6);
//mych的值输出为w
这篇就到这里。
你要知道每一天都是你改变你的生活的机会。努力朝你渴望的方向前进。为了你相信的东西,刻苦奋斗;保持你的梦想远大,减少你焦虑。你不必做得比你能做的更多;只要每天都在进步。