String类

String类的初始化:

(1)使用字符串常量直接初始化
初始化:String str = "absdefj";

(2)使用构造方法初始化

方法声明 功能描述
String() 创建一个内容为空的字符串
String(String value) 根据指定的字符串内容创建对象
String(char[] value) 根据指定的字符数组创建对象
String(byte[] bytes) 根据指定的字节数组创建对象
  1. public class Test {
  2. public static void main (String[] args) throws Exception{
  3. String str1 = new String(); // 创建一个内容为空的字符串
  4. String str2 = new String("abcd"); // 根据指定的字符串内容创建对象
  5. char[] charStr = new char[] {'D', 'E', 'F'};
  6. String str3 = new String(charStr); // 根据指定的字符数组创建对象
  7. byte[] byteStr = {39, 45, 62};
  8. String str4 = new String(byteStr); // 根据指定的字节数组创建对象
  9. }
  10. }

String类的常用操作

方法声明 功能描述
int indexOf(char ch) 返回指定字符ch在字符串中第一次出现位置的索引
int lastIndexOf(char ch) 返回指定字符ch在字符串中最后一次出现位置的索引
int indexOf(String str) 返回指定子字符串str在字符串第一次出现位置的索引
int lastIndexOf(String str) 返回指定子字符串str在此字符串中最后一次出现位置的索引
char charAt(int index) 返回字符串中index位置上的字符,其中index的取值范围是0~(字符串长度-1)
Boolean endsWith(String suffix) 判断此字符串是否以指定的字符串结尾
int length() 返回此字符串的长度
boolean equals(Object anObject) 将此字符串与指定的字符串比较
boolean isEmpty() 判断字符串长度是否为0,如果为0,则返回true;反之,则返回false
boolean startsWith(String prefix) 判断此字符串是否以指定的字符串开始
boolean contains(CharSequencecs) 判断此字符串中是否包含指定的字符序列
String toLowerCase() 使用默认语言环境的规则将String中的所有字符都转换为小写字母
String toUpperCase() 使用默认语言环境的规则将String中的所有字符都转换为大写字母
static String valueOf(int i) 将int变量i转换成字符串
char[] toCharArray() 将此字符串转换为一个字符数组
String repace(CharSequence oldstr, CharSequence newstr) 返回一个新的字符串,它是通过用newstr替换此字符串中出现的所有oldstr得到的
String[] split(String regex) 根据参数regex将原来的字符串分割为若干个子字符串
String substrng(int beginIndex) 返回一个新字符串,它包含从指定的beginIndex处开始,直到此字符串末尾的所有字符
String substring(intbegnIndex,intendIndex) 返回一个新字符串,它包含从指定的beginIndex处开始,直到索引endIndex-1处的所有字符
String trim() 返回一个新字符串,它去除了原字符串首尾的空格

程序设计实例:统计字符个数

输入一个字符串,统计字符串中大小写字母及数字字符个数。

  1. import java.util.Scanner;
  2. public class Main {
  3. public static void main(String[] args) {
  4. Scanner sc = new Scanner(System.in);
  5. System.out.print("请输入一个字符串:");
  6. String str = sc.nextLine();
  7. int bigCount = 0;
  8. int smallCount = 0;
  9. int numberCount = 0;
  10. for (int i = 0; i < str.length(); ++ i) {
  11. char ch = str.charAt(i);
  12. if (ch >= 'A' && ch <= 'Z') ++ bigCount;
  13. else if (ch >= 'a' && ch <= 'z') ++ smallCount;
  14. else if (ch >= '0' && ch <= '9') ++ numberCount;
  15. else System.out.println("该字符非法");
  16. }
  17. System.out.println("大写字符:"+bigCount+"个");
  18. System.out.println("小写字符:"+smallCount+"个");
  19. System.out.println("数字字符:"+numberCount+"个");
  20. }
  21. }

字符串常量

注意字符串是常量,它们的值在创建后不能被更改。

由于String类的对象内容不可改变,所以每当进行字符串拼接时,总是会在内存中创建一个新的对象。例如:

  1. public class StringDemo {
  2. public static void main(String[] args) {
  3. String s = "Hello";
  4. s += "World";
  5. System.out.println(s);
  6. }
  7. }

这段代码总共产生了三个字符串,即"Hello"、"World"和"HelloWorld"。引用变量s首先指向Hello对象,最终指向拼接出来的新字符串对象,即HelloWord。

String拼接问题.bmp