java学习之路:4.String类 连接字符串 获取字符串信息

写在前面:
大家好,我是 花狗Fdog ,来自内蒙古的一个小城市,目前在泰州读书。
很感谢能有这样一个平台让我能够在这里分享所学所感。
我喜欢编程,喜欢代码,喜欢去做一个程序员。
努力学习,争取多年后,给亲人更好的生活。
QQ / WX:2506897252 欢迎交流。



一.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

这篇就到这里。

若有错误,欢迎指出批评,欢迎讨论。
你要知道每一天都是你改变你的生活的机会。努力朝你渴望的方向前进。为了你相信的东西,刻苦奋斗;保持你的梦想远大,减少你焦虑。你不必做得比你能做的更多;只要每天都在进步。

发布了35 篇原创文章 · 获赞 57 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Fdog_/article/details/104128177