1、子串(substring):extract substring from a larger string
String greeting = "Hello";
String s = greeting.substring(0,3);2、拼接(concatenation):use + to join two strings or else
String expletive = "Expletive";
String PG = " deleted ";
int age = 250;
double number = 2.333;
String message = expletive + PG + age + " " + number;注意事项:当字符串与非符串拼接时,后者后被转化为字符串
3、不可变字符串
字符串不可变,若要将greeting = "Hello"修改为"Help!"只能通过如下方法(提取加拼接)修改
greeting = greeting.substring(0,3) + "p!";4、检测字符串是否相等:s.equals(t)
s 和 t 可以是变量(如greeting),也可以是常量(如"greeting")
若不区分大小写,可用equalsIgnoreCase方法:"Hello".equalsIgnoreCase("hello")
注意事项:不能使用 == ,这个只能判断是否在同一位置(地址)
5、empty and null String
如果String = null,代表没有指向一个变量
如果String = "",代表指向的是一个空变量
所以,如果null String 用 String.length()会出现错误(因为未指向)
判断变量是否为空最好用
if(String != null && String.length() != 0)5、找相应位置的字符
char first = greeting.charAt(0);//first is 'H'---------------------------------------------------------(未完待续)
附上相关实验代码:
import java.math.BigInteger;
import java.util.*;
import java.io.*;
public class String_Text
{
public static void main(String args[])
{
String greeting = "Hello";
String s = greeting.substring(0,3);
System.out.println("s = "+s);
String expletive = "Expletive";
String PG = " deleted ";
int age = 250;
double number = 2.333;
String message = expletive + PG + age + " " + number;
System.out.println("message = "+message);
System.out.println("Hello".equals(greeting));
System.out.println("Hello".equalsIgnoreCase("Hello"));
String str1 = null;
String str2 = "";
//System.out.println("str1 = "+str1.length());
System.out.println("str2 = "+str2.length());
System.out.println(str1 == null);
System.out.println(str2 == null);
char first = greeting.charAt(0);//first is 'H'
System.out.println(first);
}
}
本文详细介绍了Java中字符串的基本操作,包括子串提取、拼接、修改及比较等常见任务,并通过示例代码展示了如何实现这些功能。此外还讨论了字符串不可变性、长度检查以及字符检索的方法。
1331

被折叠的 条评论
为什么被折叠?



