String类的用法
来源:互联网 发布:淘宝号为什么会被监控 编辑:程序博客网 时间:2024/05/19 08:36
String类用法:
String不是原始类型,而是一个类(class),它被用来表示字符序列(字符串)。字符本身符合Unicode标准。
与C和C++不同,String不用'\0' 作为结束。
基本用法:
直接赋值:String s1="Hello", s2=" Java";
或者new一个String:String s1=new String("Hello");
字符串连接操作:
String s3=s1+s2; //字符串连接s3="Hello Java"
int i=10;
String str="i="+ i; //str的值为"i=10"
说明:如果字符串与其他类型变量进行“+”运算,系统将自动将其他类型转换为字符串。
int a = 1, b=2;
String str = "hello";
System.out.println(str+a+b);
System.out.println(a+b+str);
输出结果:
hello12
3hello
检测一个字符串既不是null也不是空串,就需要一下条件:
if(str != null && str.length() != 0) 首先要检查str不为null
String类常用方法:
创建新String:
String substring(int start, int end):返回一个新串,它是原串中从start到end-1的一部分。(即不包含end)
String toLowerCase():返回一个新串,它将原串中的大写字母变成小写。
String toUpperCase():返回一个新串,它将原串中的小写字母变成大写。
例:String s="Now is the time for dinner";
则 s.substring( 1,3 )="ow"
注:字符串序号值从0开始。
查找方法:
boolean endsWith(String s):如原串以s串为结尾,则返回true。
boolean startsWith(String s):如原串以s串为开始,则返回true。
int indexOf(String s):返回串中第一次出现s串的序号值。
int lastIndexOf(String s):返回串中s串最后出现的序号值。
如果没有找到则返回 -1
例:String s="I am a student";
s.indexOf("stu")=7
s.indexOf("you")=-1
s.lastIndexOf("a")=5
s.endsWith("ent")=true
注:字符串序号值从0开设。
比较方法:
boolean equals(String s):如果原串与s串相等,则返回true。
特别提醒:字符串内容的比较不能用==
equalsIgnoreCase方法:检测两个字符串是否相等,而不区分大小写。
int compareTo(String s):进行字典序比较,如果原串小于s串则返回负数;如果原串大于s串则返回正数;如果原串等于s串则返回零。
例:String s1="abc"; String s2="xyz"; 则s1.compareTo(s2)=-23
其它方法:
char charAt(int index):返回index处的字符。
int length():返回串的长度。
例:String s="student";
则s.length=7 s.charAt(2)='u'
字符串equals和==的比较:
以下输出结果是什么?
String s1="abc";
String s2="abc";
String s3=new String("abc");
String s4=new String("abc");
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
System.out.println(s3==s4);
System.out.println(s3.equals(s4));
输出结果:
true
true
false
True
int codePointAt(int index) 返回从给定位置开始或结束的代码点。
int offsetByCodePoints(int startIndex,int cpCount)返回从startIndex代码点开始,位移cpCount后的代码点索引。
- String 类的用法
- String类的用法
- String类的用法
- String 类的用法
- String类的用法
- string类的用法
- C++ string类的用法
- string类的用法总结
- C++ string类的用法
- String 类的基本用法
- C++ string类的用法
- String类的相关用法
- string类的用法详解
- C++的string类函数的用法
- C++中string类的用法概述
- String类中getChars方法的用法
- String类中toCharArray()方法的用法
- String类中getBytes()方法的用法
- 第一记— Swift版百思不得姐
- 前端问题
- Human Gene Functions
- 【杭电oj】2079 - 选课时间(母函数)
- 路径问题(如何正确写出文件路径)
- String类的用法
- C语言 函数小总结
- java之冒泡,选择,快速排序
- android 黑名单中电话拦截
- ubuntu安装python mysqldb模块
- Codeforces Round #363 (Div. 2) C. Vacations
- Android 动画 Activity切换动画
- Win7下WinDbg开启Local Kernel Debug调试
- CodeForces 1B Spreadsheets(模拟)