Java基础:第十八讲 String用法(上)
String是比较特殊的数据类型,它不属于基本数据类型,但是可以和使用基本数据类型一样直接赋值,不使用new关键字进行实例化。也可以像其他类型一样使用关键字new进行实例化。下面的代码都是合法的:
String s1 = "this is a string!";
String s2 = new String("this is another string!");
另外String在使用的时候不需要用import语句导入,还可以使用“+”这样的运算符。如果想把字符串连接起来,可以使用“+”完成。例如:s1+s2。
String的一些常用方法如下。为了说明方法,方法中使用的示例字符串为:str=“this is a test!”;
求长度
方法定义:public int length() 。
方法描述:获取字符串中的字符的个数。
例如:
str.length()
结果:
15
获取字符串中的字符
方法定义:public char charAt(int index)。
方法描述:获取字符串中的第index个字符,从0 开始。
例如:
str.charAt(3)
结果:
s
注意:是第4 个字符。
取子串
有两种形式。形式一如下:
方法定义:public String substring(int beginIndex,int endIndex)。
方法描述:获取从beginIndex 开始到endIndex 结束的子串,包括beginIndex,不包括endIndex。
例如:
str.substring(1,4)
结果:
his
形式二如下:
方法定义:public String substring(int beginIndex)
方法描述:获取从beginIndex 开始到结束的子串
例如:
str.substring(5)
结果:
is a test!
定位字符或者字符串
有4种形式。形式一如下:
方法定义:public int indexOf(int ch)
方法描述:定位参数所指定的字符。
例如:
str.indexOf(‘i’)
结果:
2
形式二如下:
方法定义:public int indexOf(int ch,int index)
方法描述:从index开始定位参数所指定的字符。
例如:
str.indexOf(‘i’,4)
结果:
5
形式三如下:
方法定义:public int indexOf(String str)
方法描述:定位参数所指定的字符串。
例如:
str.indexOf("is")
结果:
2
形式4如下:
方法定义:public int indexOf(String str,int index)
方法描述:从index开始定位str所指定的字符串。
例如:
str.indexOf("is",6)
结果:
-1表示没有找到
替换字符和字符串
有3种形式。形式一如下:
方法定义:public String replace(char c1,char c2)
方法描述:把字符串中的字符c1替换成字符c2
例如:
str.replace('i','
相关文档:
Java NIO API详解
在JDK
1.4以前,Java的IO操作集中在java.io这个包中,是基于流的阻塞(blocking)API。对于大多数应用来说,这样的API使用很方
便,然而,一些对性能要求较高的应用,尤其是服务端应用,往往需要一个更为有效的方式来处理IO。从JDK 1.4起,NIO
API作为一个基于缓冲区,并能提供非阻塞(non-blo ......
今天看到一道题目,是这样的:(我在里面打印了一些语句,先注释掉了)
class Singleton {
private static Singleton obj= new Singleton();
public static int counter1;
public static int counter2 = 2;
private Singleton() {
counter1++;
counter2++;
// System.out.println("Singleton counter1:" ......
package io;
import java.io.*;
/**
* @author 高枕吴忧
* 利用缓冲区原理,BufferedInputStream,
* 实现的文件字节流读取功能示范
*
*/
public class BufferedInOutputStream {
public BufferedInOutputStream() {
ioTest2();
}
public void ioTest2() {
FileInputStream in = null ;
Buffered ......
StringBuffer也是字符串,与String不同的是StringBuffer对象创建完之后可以修改内容。有如下构造函数:
n public StringBuffer(int);
n public StringBuffer(String);
n ......