字符串类String
实例79 创建字符串类
package Chapter06.string;
public class StringDemo_01 {
public static void main(String[] args) {
String str0, str1, str2, str3, str4, str5, str6, str7;
byte B_array[] = { (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd',
(byte) 'e', (byte) 'f' };
char C_array[] = { '大', '家', '好', '谢', '谢', '你' };
StringBuffer sb = new StringBuffer("早上好");
str0 = new String("Goodbye"); // 根据指定的信息创建一个新的String对象
str1 = new String(); // 创建一个新的空序列String对象
str2 = new String(B_array); // 根据指定的字符集字节数组创建一个新的String对象
str3 = new String(C_array); // 根据指定的字符数组创建一个新的String对象
str4 = new String(sb); // 根据指定的字符串缓冲区参数创建一个新的String对象
str5 = new String(B_array, 1, 4); // 从B_array数组中获取以下标为1开始,下标为4-1结束之间的字节创建一个新的String对象
str6 = new String(C_array, 0, 3); // 从C_array数组中获取以下标为0开始,下标为3-1结束之间的字符创建一个新的String对象
str7 = new String(str2); // 根据指定的字符串对象创建一个新的String对象
System.out.println("创建字符串类的方法一:str0=" + str0);
System.out.println("创建字符串类的方法二:str1=" + str1);
System.out.println("创建字符串类的方法三:str2=" + str2);
System.out.println("创建字符串类的方法四:str3=" + str3);
System.out.println("创建字符串类的方法五:str4=" + str4);
System.out.println("创建字符串类的方法六:str5=" + str5);
System.out.println("创建字符串类的方法七:str7=" + str6);
System.out.println("创建字符串类的方法八:str8=" + str7);
}
}
实例80 如何使用charAt方法计算重复字符
package Chapter06.string;
import java.util.Scanner;
public class StringDemo_02 {
public static void main(String[] args) {
System.out.println("String类中的charAt方法的使用实例如下:");
String str = "ifsagdsfdsdfdfsa";
System.out.println("请输入一个字符:");
Scanner sc = new Scanner(System.in); // 创建Scanner对象
char ch = sc.next().charAt(0); // 从键盘中输入的字符串中选取第一个字符
int num = 0; // 计算字符数量和
for (int i = 0; i < str.length(); i++) { // 利用for循环依次获取字符与字符ch进行比较,如果相等,num自动加1
if (str.charAt(i) == ch)
num++;
}
System.out.println("该字符串中" + ch + "的数量为:" + num);
}
}
实例81 按字母顺序比较大小
package Chapter06.string;
public class StringDemo_03 {
public static void main(String[] args) {
String str0 = "girl"; // 创建String类对象str0,并对其进行初始化
String str1 = "gOod"; // 创建String类对象str1,并对其进行初始化
int n = str0.compareTo(str1); // 使用compareTo方法进行两个字符串的比较
int n1 = str0.compareToIgnoreCase(str1); // 使用compareToIgnoreCase方法进行两个字符串的比较
System.out.println("使用compareTo方法比较的结果如下:");
System.out.println(n > 0 ? str0 + "大于" + str1 : str0 + "小于" + str1);
System.out.println("使用compareToIgnoreCase方法比较的结果如下:");
System.out.println(n1 > 0 ? str0 + "大于" + str1 : str0 + "小于" + str1);
}
}
实例82 首尾相连
package Chapter06.string;
public class StringDemo_04 {
public static void main(String[] args) {
System.out.println("String类的concat方法使用的示例如下:");
String s = "abcd";
String s1 = "efgh";
String s2 = "ijklm";
s = s.concat(s1); // 调用concat方法,将s1追加到s的后面
s = s.concat(s2); // 调用concat方法,将s2追加到s的后面
System.out.println("最后的结果是 s=" + s);
}
}
实例83 字符串间的比较
package Chapter06.string;
public class StringDemo_05 {
public static void main(String[] args) {
String str = "admin";
String str1 = "admin";
String str2 = "ADMIN";
System.out.println("使用equals判断两个字符串是否相等:");
if (str.equals(str1)) {// 在不忽略大小写的情况下比较str和str1是否相等
System.out.println(str + "与" + str1 + "相等吗?结果为true");
} else {
System.out.println(str + "与" + str1 + "相等吗?结果为false");
}
if (str.equals(str2)) {// 在不忽略大小写的情况下比较str和str2是否相等
System.out.println(str + "与" + str2 + "相等吗?结果为true");
} else {
System.out.println(str + "与" + str2 + "相等吗?结果为false");
}
System.out.println("\n使用equalsIgnoreCase判断两个字符串是否相等:");
if (str.equalsIgnoreCase(str1)) {// 在忽略大小写的情况下比较str和str1是否相等
System.out.println(str + "与" + str1 + "相等吗?结果为true");
} else {
System.out.println(str + "与" + str1 + "相等吗?结果为false");
}
if (str.equalsIgnoreCase(str2)) {// 在忽略大小写的情况下比较str和str2是否相等
System.out.println(str + "与" + str2 + "相等吗?结果为true");
} else {
System.out.println(str + "与" + str2 + "相等吗?结果为false");
}
}
}
实例84 字符集的解码方法
package Chapter06.string;
public class StringDemo_06 {
public static void main(String[] args) throws Exception {
// ISO8859-1:拉丁文
System.out.println("ISO8859-1字符集与gb2312之间的转换:");
String str = new String("大家好".getBytes("gb2312"), "ISO8859-1"); // 将gb2312字符集转码为ISO8859-1字符集
String str1 = new String(str.getBytes("ISO8859-1"), "gb2312"); // 将ISO8859-1字符集转码为gb2312字符集
System.out.println("ISO8859-1字符集:" + str + "\ngb2312字符集:" + str1);
// KOI8:俄文
System.out.println("\nKOI8字符集与gb2312之间的转换:");
String str2 = new String("你好".getBytes("gb2312"), "KOI8"); // 将gb2312字符集转码为KOI8字符集
String str3 = new String(str2.getBytes("KOI8"), "gb2312"); // 将KOI8字符集转码为gb2312字符集
System.out.println("KOI8字符集:" + str2 + "\ngb2312字符集:" + str3);
// Big5:繁体中文
System.out.println("\nBig5字符集与gb2312之间的转换:");
String str4 = new String("谢谢你".getBytes("gb2312"), "Big5"); // 将gb2312字符集转码为Big5字符集
String str5 = new String(str4.getBytes("Big5"), "gb2312"); // 将Big5字符集转码为gb2312字符集
System.out.println("Big5字符集:" + str4 + "\ngb2312字符集:" + str5);
// ISO8859-5:西里尔文
System.out.println("\nISO8859-5字符集与gb2312之间的转换:");
String str6 = new String("美丽的中国".getBytes("gb2312"), "ISO8859-5"); // 将gb2312字符集转码为ISO8859-5字符集
String str7 = new String(str6.getBytes("ISO8859-5"), "gb2312"); // 将ISO8859-5字符集转码为gb2312字符集
System.out.println("ISO8859-5字符集:" + str6 + "\ngb2312字符集:" + str7);
}
}
实例85 寻找指定字符第一次出现的位置
package Chapter06.string;
public class StringDemo_07 {
public static void main(String[] args) {
System.out.println("String类的indexOf方法的使用示例如下:");
String str = "Looking for the first time in the specified character position";
int a = str.indexOf("f".codePointAt(0)); // 返回第一次出现指定字符的Unicode代码处的索引
int b = str.indexOf("a"); // 返回字符a第一次出现的位置
int c = str.indexOf("p".codePointAt(0), 3); // 返回从指定的索引开始搜索,第一次出现指定字符的Unicode代码的索引
int d = str.indexOf("m", 5); // 返回指定字符从指定的索引处开始,第一次出现的索引
System.out.println("a = " + a + " str.charAt(a)=" + str.charAt(a));
System.out.println("b = " + b + " str.charAt(b)=" + str.charAt(b));
System.out.println("c = " + c + " str.charAt(c)=" + str.charAt(c));
System.out.println("d = " + d + " str.charAt(d)=" + str.charAt(d));
}
}
实例86 寻找指定字符最后出现的位置
package Chapter06.string;
public class StringDemo_08 {
public static void main(String[] args) {
System.out.println("String类的lastIndexOf方法的使用示例如下:");
String str = "Characters to find the specified location last seen";
int a = str.lastIndexOf("d".codePointAt(0)); // 返回最后一次出现指定字符的Unicode代码处的索引
int b = str.lastIndexOf("a"); // 返回字符a最后一次出现的位置
int c = str.lastIndexOf("i".codePointAt(0), 23);// 返回从指定的索引向前开始搜索,最后一次出现指定字符的Unicode代码的索引
int d = str.lastIndexOf("e", 25);// 返回指定字符从指定的索引处从右向左开始搜索,最后一次出现的索引
System.out.println("a = " + a + " str.charAt(a)=" + str.charAt(a));
System.out.println("b = " + b + " str.charAt(b)=" + str.charAt(b));
System.out.println("c = " + c + " str.charAt(c)=" + str.charAt(c));
System.out.println("d = " + d + " str.charAt(d)=" + str.charAt(d));
}
}
实例87 我究竟有多长
package Chapter06.string;
public class StringDemo_09 {
public static void main(String[] args) {
System.out.println("String类的length方法的使用示例如下:");
String str = "kdflsakflsdfjsahdksl;fjsksdlkf;fl";
int len = str.length();
System.out.println("字符串:\n" + str + "的长度为:" + len);
}
}
实例88 替换指定的字符
package Chapter06.string;
public class StringDemo_10 {
public static void main(String[] args) {
String str = "我很欣赏你,因为你是个好人";
String newStr = str.replace('你', '他'); // 调用replace方法,将字符串str中的字符'你'换成'他'
System.out.println("替换前的字符串的内容如下:\n " + str);
System.out.println("\n替换后的字符串的内容如下:\n " + newStr);
}
}
实例89 分割字符串
package Chapter06.string;
public class StringDemo_11 {
public static void main(String[] args) {
String str = "One:and:Two:is:Three";
String[] s = str.split(":");
String[] s1 = str.split(":", 2);
String[] s2 = str.split(":", 6);
String[] s3 = str.split(":", -2);
System.out.println("str.split(\":\")的结果如下:");
for (int i = 0; i < s.length; i++) {
System.out.print(" " + s[i]);
}
System.out.println("\nstr1.split(\":\",2)的结果如下:");
for (int i = 0; i < s1.length; i++) {
System.out.print(" " + s1[i]);
}
System.out.println("\nstr2.split(\":\",6)的结果如下:");
for (int i = 0; i < s2.length; i++) {
System.out.print(" " + s2[i]);
}
System.out.println("\nstr3.split(\":\",-2)的结果如下:");
for (int i = 0; i < s3.length; i++) {
System.out.print(" " + s3[i]);
}
}
}
实例90 如何使用substring方法截取子串
package Chapter06.string;
public class StringDemo_12 {
public static void main(String[] args) {
String str = "I am a student and he is a teacher";
String sub1 = str.substring(19); // 返回一个从指定索引处开始截取的新字符串
String sub2 = str.substring(0, 14); // 返一个从索引为0开始截取到索引为14结束的新字符串
System.out.println("str.substring(19)的结果为:\n " + sub1);
System.out.println("str.substring(0, 14)的结果为:\n " + sub2);
}
}
实例91 分解字符串
package Chapter06.string;
public class StringDemo_13 {
public static void main(String[] args) {
String str = "abcdefghijklmnopqrstuvwxyz";
char[] arr = str.toCharArray(); // 调用String类的toCharArray方法,将字符串转换成字符数组
System.out.println("char型数组arr中的数组元素如下:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
if ((i + 1) % 7 == 0)
System.out.println();
}
}
}
实例92 字母大小写转换
package Chapter06.string;
public class StringDemo_14 {
public static void main(String[] args) {
String s = "HELLO KITTY";
String s1 = "good morning";
System.out.println("大写字母变成小写字母:" + s.toLowerCase());
System.out.println("小写字母变成大写字母:" + s1.toUpperCase());
}
}
实例93 去除多余的空白
package Chapter06.string;
public class StringDemo_15 {
public static void main(String[] args) {
String str = " 你好 ";
String str1 = str.trim(); //将指定字符串的首尾的空白字符去掉
System.out.println("字符串str的字符长度为:"+str.length());
System.out.println("字符串str1的字符长度为:"+str1.length());
}
}
实例94 原始数组类型的String形式
package Chapter06.string;
public class StringDemo_16 {
public static void main(String[] args) {
char[] ch = { 'a', 'A', 'b', 'B', 'c' };
String sb = String.valueOf(true); // boolean转换成String
String sf = String.valueOf(12.50f); // float转换成String
String sd = String.valueOf(15269.00012); // double转换成String
String sc = String.valueOf('\"'); // char转换成String
String si = String.valueOf(456); // int转换成String
String sl = String.valueOf(100202l); // long转换成String
String sch = String.valueOf(ch); // 字符数组转换成String
String sch1 = String.valueOf(ch, 1, 3); // 将部分字符数组转换成String
System.out.println("boolean数据的字符串表示形式:" + sb);
System.out.println("float数据的字符串表示形式: " + sf);
System.out.println("double数据的字符串表示形式: " + sd);
System.out.println("char数据的字符串表示形式: " + sc);
System.out.println("int数据的字符串表示形式: " + si);
System.out.println("long数据的字符串表示形式: " + sl);
System.out.println("字符数组的字符串表示形式: " + sch);
System.out.println("部分字符数组的字符串表示形式: " + sch1);
}
}
实例95 Java合法标识符
package Chapter06.string;
public class StringDemo_17 {
public static boolean isIdentifier(String s) {
// 如果字符串为空或者长度为0,返回false
if ((s == null) || (s.length() == 0)) {
return false;
}
// 字符串中每一个字符都必须是Java标识符的一部分
for (int i = 0; i < s.length(); i++) {
if (!Character.isJavaIdentifierPart(s.charAt(i))) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println("\"test_1\" 是一个标识符吗? "
+ StringDemo_17.isIdentifier("test_1"));
System.out.println("\"test.1\" 是一个标识符吗? "
+ StringDemo_17.isIdentifier("test.1"));
System.out.println("\"$test\" 是一个标识符吗? "
+ StringDemo_17.isIdentifier("$test"));
System.out.println("\"\u0391test\" 是一个标识符吗? "
+ StringDemo_17.isIdentifier("\u0391test"));
System.out.println("\"\0$var-2\" 是一个标识符吗? "
+ StringDemo_17.isIdentifier("\0$var-"));
}
}
实例96 显示一周各星期的名称
package Chapter06.string;
public class StringDemo_18 {
public static void main(String[] args) {
String week = "日一二三四五六";
System.out.println("第一种方法:");
for (int i = 0; i < week.length(); i++) { // 通过charAt方法获取单个字符
System.out.print("星期" + week.charAt(i) + " ");
}
System.out.println("\n第二种方法:");
for (int i = 0; i < week.length(); i++) { // 通过substring方法获取单个字符
String c = week.substring(i, i + 1);
System.out.print("周" + c + " ");
}
}
}
实例97 构造空心方框
package Chapter06.string;
import java.util.Scanner;
public class StringDemo_19 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入宽为:");
int w = sc.nextInt() ;// 从键盘中获取w的值
System.out.println("请输入高为:");
int h = sc.nextInt(); // 从键盘中获取h的值
drawArea(w, h);
}
public static void drawArea(int w, int h) {
for (int i = w; i > 0; i--) { // 画长度为w的第一条边
System.out.print("#");
}
System.out.println();
for (int i = h - 2; i > 0; i--) { // 画由"#"和空格组成的空心框
System.out.print("#");
for (int j = w - 2; j > 0; j--) {
System.out.print(" ");
}
System.out.print("#");
System.out.println();
}
for (int i = w; i > 0; i--) { // 画长度为w的第二条边
System.out.print("#");
}
System.out.println();
}
}
实例98 这一天是星期几
package Chapter06.string;
import java.util.Scanner;
public class StringDemo_20 {
public static void main(String[] args) {
System.out.println("请输入参数,多个参数以逗号分开:");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String arr[] = str.split(",");
switch (arr.length) {// 根据数组的长度来决定掉用哪个方法
case 1:
System.out.println(arr[0] + "年是"
+ year(Integer.valueOf(arr[0]).intValue()));
break;
case 2:
System.out.println(arr[0]
+ "年"
+ arr[1]
+ "月有"
+ month(Integer.valueOf(arr[0]).intValue(), Integer
.valueOf(arr[1]).intValue()) + "天");
break;
case 3:
System.out.println(arr[0]
+ "年"
+ arr[1]
+ "月"
+ arr[2]
+ "日是星期"
+ day(Integer.valueOf(arr[0]).intValue(), Integer.valueOf(
arr[1]).intValue(), Integer.valueOf(arr[2])
.intValue()));
break;
default:
System.out.println("您输入的参数有误!");
}
}
public static String year(int y) {// 判断该年是不是闰年
String leap = (y % 400 == 0 || y % 4 == 0 && y % 100 != 0) ? "闰年"
: "平年";
return leap;
}
public static int month(int y, int m) {// 计算指定年份的某个月有多少天
System.out.println(m);
int days = 0;
String leap = year(y);
if (m > 7) {
if (m % 2 == 0) {
days = 31;
} else {
days = 30;
}
} else {
if (m % 2 == 0) {
days = 31;
} else {
days = 30;
}
if (m == 2 && leap.equals("闰年")) {
days = 29;
} else if (m == 2 && leap.equals("平年")) {
days = 28;
}
}
return days;
}
public static String day(int y, int m, int d) {// 求出某年某月某日的这一天是星期几
if (m == 1 || m == 2) {
m += 12;
y--;
}
int week = d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400
+ 1;
week = week % 7;
String w = "日一二三四五六".substring(week, week + 1);
return w;
}
}
实例99 大小写互换
package Chapter06.string;
public class StringDemo_21 {
public static void main(String[] args) {
String str = "Miss Li is a Teacher,Cycling to work every morning";
System.out.println("原字符串如下:\n " + str);
char arr[] = str.toCharArray(); // 将字符串转化成char型数组
for (int i = 0; i < arr.length; i++) {
if (arr[i] >= 65 && arr[i] < 91) { // 判断是否是大写字母
arr[i] = (arr[i] + "").toLowerCase().charAt(0); // 如果是将当前字符的值由大写变小写
} else if (arr[i] >= 97 && arr[i] < 123) { // 判断是否是小写字母
arr[i] = (arr[i] + "").toUpperCase().charAt(0); // 如果是将当前字符的值由小写变大写
}
}
String s = new String(arr); // 将char型数组转换成字符串
System.out.println("大小写字母互换后的字符串如下:\n " + s);
}
}
实例100 输出指定范围的素数
package Chapter06.string;
public class StringDemo_22 {
static int[] a = null;
static int b = 0;
private static boolean isPrime(int n){//判断n是素数的方法
for(int i=2;i<n;i++){
if(n%i==0)
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println("50和" + "300之间的所有素数如下:");
for(int i=50;i<=300;i++){
if(isPrime(i)==true){
System.out.print(i+"\t");
b++;
if(b%5==0){
System.out.println();
}
}
}
}
}
实例101 我出现了几次
package Chapter06.string;
public class StringDemo_22 {
static int[] a = null;
static int b = 0;
private static boolean isPrime(int n){//判断n是素数的方法
for(int i=2;i<n;i++){
if(n%i==0)
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println("50和" + "300之间的所有素数如下:");
for(int i=50;i<=300;i++){
if(isPrime(i)==true){
System.out.print(i+"\t");
b++;
if(b%5==0){
System.out.println();
}
}
}
}
}
实例102 算术表达式求值器
package Chapter06.string;
public class StringDemo_24 {
public static final int NULL_MARK = 0; // 标记为空或者结束符
public static final int SEPARATION_MARK = 1; // 标记为分隔符
public static final int VAR_MARK = 2; // 标记为变量
public static final int NUM_MARK = 3; // 标记为数字
public static final int GRAMMAR_Exception = 0; // 语法错误
public static final int UNEND_Exception = 1; // 括号没有结束错误
public static final int NULLEXP_Exception = 2; // 表达式为空错误
public static final int BYZERO_Exception = 3; // 被0除错误
public static final String[] MESSAGES_Exception = { "语法错误", "大括号没有成对错误",
"表达式为空错误", "被0除错误" };
public static final String END = "\0"; // 表达式的结束标记
private String expre; // 表达式字符串
private int position; // 求值器当前指针在表达式中的位置
private String current; // 求值器当前处理的标记
private int currentType; // 求值器当前处理标记的类型
private double varArray[] = new double[26]; // 变量的数组
/** 求值一个表达式,返回表达式的值。 */
public double analysis(String str) throws Exception {
double result;
this.expre = str;
this.position = 0;
// 获取第一个标记
this.getMark();
if (this.current.equals(END)) {
// 没有表达式异常
this.proce_Exception(NULLEXP_Exception);
}
result = this.proce_Evalua(); // 处理赋值语句
// 处理完赋值语句,应该就是表达式结束符,如果不是,则返回异常
if (!this.current.equals(END)) {
this.proce_Exception(GRAMMAR_Exception);
}
return result;
}
private double proce_Evalua() throws Exception {
double result; // 结果
int var_Index; // 变量下标
String oldMark; // 旧标记
int oldMarkType; // 旧标记的类型
// 如果标记类型是变量
if (this.currentType == VAR_MARK) {
// 保存当前标记
oldMark = new String(this.current);
oldMarkType = this.currentType;
// 取得变量的索引,本求值器只支持一个字目的变量,
// 如果用户的变量字母长度大于1,则取第一个字母当作变量
var_Index = Character.toUpperCase(this.current.charAt(0)) - 'A';
// 获得下一个标记
this.getMark();
// 如果当前标记不是等号=
if (!this.current.equals("=")) { // 判断当前表达式是否是赋值运算
this.rollBack(); // 回滚
// 不是一个赋值语句,将标记恢复到上一个标记
this.current = new String(oldMark);
this.currentType = oldMarkType;
} else {
// 如果当前标记是等号=,即给变量赋值,形式如a = 3 + 5;
// 则计算等号后面表达式的值,然后将得到的值赋给变量
this.getMark();
// 因为加减法的优先级最低,所以计算加减法表达式。
result = this.arith_AddExpre();
// 将表达式的值赋给变量,并存在实例变量vars中。
this.varArray[var_Index] = result;
return result;
}
}
return this.arith_AddExpre(); // 调用arith_AddExpre方法,进行加减法计算表达式的值。
}
private double arith_AddExpre() throws Exception {
char op; // 操作符
double result; // 结果
double partialResult; // 当前子表达式的结果
result = this.arith_MulExpre(); // 调用arith_MulExpre方法获取当前子表达式的值
// 当前标记的第一个字母是加减号,则继续进行加减法运算。
while ((op = this.current.charAt(0)) == '+' || op == '-') {
this.getMark(); // 取下一个标记
partialResult = this.arith_MulExpre(); // 调用arith_MulExpre方法获取当前子表达式的值
switch (op) {
case '-':
// 如果是减法,则用已处理的子表达式的值减去当前子表达式的值
result = result - partialResult;
break;
case '+':
// 如果是加法,用已处理的子表达式的值加上当前子表达式的值
result = result + partialResult;
break;
}
}
return result;
}
private double arith_MulExpre() throws Exception {
char op; // 运算符
double result; // 表达式结果
double currentResult; // 子表达式的结果
// 用指数运算计算当前子表达式的值
result = this.indexExpre();
// 如果当前标记的第一个字母是乘、除或者取模运算符,则继续进行乘除法运算。
while ((op = this.current.charAt(0)) == '*' || op == '/' || op == '%') {
this.getMark(); // 取下一个标记
// 用指数运算计算当前子表达式的值
currentResult = this.indexExpre();
switch (op) {
case '*':
// 如果是乘法,则用已处理子表达式的值乘以当前子表达式的值
result = result * currentResult;
break;
case '/':
// 如果是除法,判断当前子表达式的值是否为0,如果为0,则抛出被0除异常
// 除数不能为0
if (currentResult == 0.0) {
this.proce_Exception(BYZERO_Exception);
}
// 除数不为0,则进行除法运算
result = result / currentResult;
break;
case '%':
// 如果是取模运算,也要判断当前子表达式的值是否为0
// 如果为0,则抛出被0除异常
if (currentResult == 0.0) {
this.proce_Exception(BYZERO_Exception);
}
// 进行取模运算
result = result % currentResult;
break;
}
}
return result;
}
private double unaryOperator() throws Exception {
double result; // 表达式结果
String op; // 运算符
op = "";
// 如果当前标记类型为分隔符,而且分隔符的值等于+或者-。
if ((this.currentType == SEPARATION_MARK) && this.current.equals("+")
|| this.current.equals("-")) {
op = this.current;
this.getMark();
}
// 用括号运算计算当前子表达式的值
result = this.parenthesis();
if (op.equals("-")) {
// 如果操作符为-,则表示负数,将子表达式的值变为负数
result = -result;
}
return result;
}
private double parenthesis() throws Exception {
double result; // 表达式结果
if (this.current.equals("(")) { // 如果当前标记为左括号,则表示是一个括号运算
this.getMark(); // 取下一个标记
result = this.arith_AddExpre(); // 调用arith_AddExpre方法
// 判断括圆括号是否匹配,如果当前标记不等于右括号,抛出括号不匹配异常
if (!this.current.equals(")")) {
this.proce_Exception(UNEND_Exception);
}
this.getMark(); // 否则取下一个标记
} else {
// 如果标记不是左括号,表示不是一个括号运算,则调用varNumber方法
result = this.varNumber();
}
return result;
}
private double varNumber() throws Exception {
double result = 0.0; // 结果
switch (this.currentType) {
case NUM_MARK:
// 如果当前标记类型为数字
try {
// 将数字的字符串转换成数字值
result = Double.parseDouble(this.current);
} catch (NumberFormatException exc) {
this.proce_Exception(GRAMMAR_Exception);
}
this.getMark(); // 取下一个标记
break;
case VAR_MARK:
// 如果当前标记类型是变量,则取变量的值
result = this.seekVar(current);
this.getMark();
break;
default:
this.proce_Exception(GRAMMAR_Exception);
break;
}
return result;
}
private double seekVar(String vname) throws Exception {
// 判断是否有语法异常发生,如果变量的第一个字符不是字母,则抛出语法异常
if (!Character.isLetter(vname.charAt(0))) {
proce_Exception(GRAMMAR_Exception);
return 0.0;
}
// 从实例变量数组varArray中取出该变量的值
return varArray[Character.toUpperCase(vname.charAt(0)) - 'A'];
}
private double indexExpre() throws Exception {
double result; // 表达式结果
double currentResult; // 子表达式的值
double ex; // 指数的底数
int t; // 指数的幂
result = this.unaryOperator(); // 调用unaryOperator方法,获取当前表达式中的底数值
if (this.current.equals("^")) { // 如果当前标记为"^"运算符,则为指数计算
// 获取下一个标记,即获取指数的幂
this.getMark();
currentResult = this.indexExpre();
ex = result;
if (currentResult == 0.0) {
// 如果指数的幂为0,则指数的值为1
result = 1.0;
} else {
// 否则,指数的值为个数为指数幂的底数相乘的结果。
for (t = (int) currentResult - 1; t > 0; t--) {
result = result * ex;
}
}
}
return result;
}
private void rollBack() {
if (this.current == END) {
return;
}
// 求值器当前指针往前移动
for (int i = 0; i < this.current.length(); i++) {
this.position--;
}
}
private void proce_Exception(int errorType) throws Exception {
// 遇到异常情况时,根据错误类型,取得异常提示信息,将提示信息封装在异常中抛出
throw new Exception(MESSAGES_Exception[errorType]);
}
private void getMark() {
// 设置初始值
this.currentType = NULL_MARK;
this.current = "";
// 判断表达式是否结束,如果求值器当前指针等于字符串的长度则表示表达式已经结束
if (this.position == this.expre.length()) {
this.current = END; // 如果表达式已经结束,则设置当前标记的置为END。
return;
}
while (this.position < this.expre.length() // 当遇到表达式中的空白符则跳过
&& Character.isWhitespace(this.expre.charAt(this.position))) {
++this.position;
}
if (this.position == this.expre.length()) { // 判断当前表达式是否结束
this.current = END;
return;
}
char currentChar = this.expre.charAt(this.position); // 取得求值器当前指针指向的字符
if (isSepara(currentChar)) { // 如果当前字符是一个分隔符,则认为这是一个分隔符标记,
this.current += currentChar; // 给当前标记和标记类型赋值,并将指针后移
this.position++;
this.currentType = SEPARATION_MARK;
} else if (Character.isLetter(currentChar)) {// 判断当前字符是否是一个字母
while (!isSepara(currentChar)) { // 依次求值该变量的组成部分,直到遇到一个分隔符为止
this.current += currentChar;
this.position++;
if (this.position >= this.expre.length()) {
break;
} else {
currentChar = this.expre.charAt(this.position);
}
}
this.currentType = VAR_MARK; // 设置标记类型为变量
} else if (Character.isDigit(currentChar)) { // 判断当前字符是否是一个数字
while (!isSepara(currentChar)) { // 依次求值该数字的组成部分,直到遇到一个分隔符为止
this.current += currentChar;
this.position++;
if (this.position >= this.expre.length()) {
break;
} else {
currentChar = this.expre.charAt(this.position);
}
}
this.currentType = NUM_MARK; // 设置标记类型为数字
} else {
// 如果是无法识别的字符,则设置表达式结束
this.current = END;
return;
}
}
private boolean isSepara(char c) {
if ((" +-/*%^=()".indexOf(c) != -1))
return true;
return false;
}
public static void main(String[] args) throws Exception {
StringDemo_24 sd24 = new StringDemo_24();
double a = 15.0, b = 7.0;
String express1 = "a = 15.0";
System.out.println("表达式1:(\"a = 15.0\") = " + sd24.analysis(express1));
String express2 = "b = 7.0";
System.out.println("表达式2:(\"b = 7.0\") = " + sd24.analysis(express2));
String express3 = "(a+b) * (a-b)";
System.out.println("表达式3:(\"(" + a + "+" + b + ") * (" + a + "-" + b
+ ")\") = " + sd24.analysis(express3));
String express4 = "2*6-7/2";
System.out.println("表达式4:(\"2*6-7/2\") = " + sd24.analysis(express4));
String express5 = "(8-3)*((a+b)/(a-b))";
System.out.println("表达式5:(\"(8-3)*((" + a + "+" + "+" + b + ")/(" + a
+ "-" + b + "))\") = " + sd24.analysis(express5));
String express6 = "13 % 2";
System.out.println("表达式6:(\"13%2\") = " + sd24.analysis(express6));
String express7 = "4^3 * 8 + 2";
System.out
.println("表达式7:\"3^2 * 5 + 4\") = " + sd24.analysis(express7));
}
}
实例103 字符串对齐调整器
package Chapter06.string;
public class StringDemo_25 {
public static final int LEFT = 0; // 左对齐格式
public static final int CENTER = 1; // 居中格式
public static final int RIGHT = 2; // 右对齐格式
private int format; // 当前对齐格式
private int maxLength; // 一行的最大长度
/** 默认构造函数 */
public StringDemo_25() {
// 默认为居中对齐,一行的最大长度为80
this.format = CENTER;
this.maxLength = 80;
}
/** 构造一个字符串对齐器,需要传入一行的根据最大长度和对齐的格式。 */
public StringDemo_25(int maxLength, int format) {
this(); // 首先构造一个默认字符串对齐器
// 根据传入参数修改字符串对齐器的属性
this.setFormat(format);
this.setMaxLength(maxLength);
}
/** 将字符串按指定的对齐格式进行齐 */
public String format(String s) {
StringBuffer where = new StringBuffer();
// 获得一个新长度为行最大长度和s长度的较小值
int wLength = Math.min(s.length(), this.maxLength);
String w = s.substring(0, wLength); // 根据新长度从待对齐的字符串s中获取一个子串
switch (this.format) { // 根据对齐模式,选择空格的合适的位置
case RIGHT:
// 如果是右对齐,则空格放在左边
addSpace(where, maxLength - wLength);
// 将字符串添加在右边
where.append(w);
break;
case CENTER:
// 居中对齐,将空格字符平均分在字符串两边。
int start = where.length();
addSpace(where, (maxLength - wLength) / 2);
where.append(w);
addSpace(where, (maxLength - wLength) / 2);
// 调整舍入误差
addSpace(where, maxLength - (where.length() - start));
break;
case LEFT:
// 右对齐,将空格字符放在字符串右边。
where.append(w);
addSpace(where, maxLength - wLength);
break;
}
// 如果原字符串的长度大于一行的最大长度,则将余下部分放入下一行
if (s.length() > wLength) {
String remainStr = s.substring(wLength);
where.append("\n" + this.format(remainStr));
}
return where.toString();
}
/** 追加空格字符。 */
protected final void addSpace(StringBuffer to, int howMany) {
for (int i = 0; i < howMany; i++)
to.append(" ");
}
public int getFormat() {
return format;
}
/** 设置对齐的格式 */
public void setFormat(int format) {
switch (format) {
case LEFT:
case CENTER:
case RIGHT:
this.format = format;
break;
default:
System.out.println("无效的对齐格式");
}
}
public int getMaxLength() {
return maxLength;
}
/** 设置字符串一行中最多可以显示的字符数 */
public void setMaxLength(int maxLength) {
if (maxLength < 0) {
System.out.println("最大长度的值必须大于0.");
} else {
this.maxLength = maxLength;
}
}
public static void main(String[] args) {
System.out.println("字符的居中对齐方式如下:");
StringDemo_25 formatter = new StringDemo_25(15, StringDemo_25.CENTER);// 一行最多15个字符,居中显示
System.out.println(formatter.format("123456"));
System.out.println(formatter.format(Integer.toString(56)));
System.out.println(formatter.format("abcdefghijklmnopqrstuvwxyz"));
System.out.println("\n字符的左对齐方式如下:");
formatter = new StringDemo_25(15, StringDemo_25.LEFT); // 一行最多15个字符,左对齐显示
System.out.println(formatter.format("&%54$$"));
System.out.println(formatter.format(Integer.toString(83)));
System.out.println(formatter.format("abcdefghijklmnopqrstuvwxyz"));
System.out.println("\n字符的右对齐方式如下:"); // 一行最多15个字符,右对齐显示
formatter = new StringDemo_25(15, StringDemo_25.RIGHT);
System.out.println(formatter.format("123456"));
System.out.println(formatter.format(Integer.toString(8)));
System.out.println(formatter.format("abcdefghijklmnopqrstuvwxyz"));
}
}
实例104 字符串的加密
package Chapter06.string;
import java.security.MessageDigest;
public class StringDemo_26 {
private final static String[] hexArray = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; // 存储十六进制值的数组
/** 根据指定的字符串,创建加密后的字符串 */
public static String createEncrypPassword(String string) {
return encrypByMD5(string);
}
/** 检验输入的密码是否正确 */
public static boolean verificationPassword(String password, String string) {
if (password.equals(encrypByMD5(string))) {
return true;
} else {
return false;
}
}
/** 对指定的字符串进行MD5加密 */
private static String encrypByMD5(String originString) {
if (originString != null) {
try {
// 创建具有MD5算法的信息摘要
MessageDigest md = MessageDigest.getInstance("MD5");
// 使用指定的字节数组对摘要进行最后更新,然后完成摘要计算
byte[] results = md.digest(originString.getBytes());
// 将得到的字节数组变成字符串返回
String resultString = byteArrayToHex(results);
return resultString.toUpperCase();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}
/** 将字节数组转换成16进制,并以字符串的形式返回 */
private static String byteArrayToHex(byte[] b) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
resultSb.append(byteToHex(b[i]));
}
return resultSb.toString();
}
/** 将一个字节转换成16进制,并以字符串的形式返回 */
private static String byteToHex(byte b) {
int n = b;
if (n < 0)
n = 256 + n;
int d1 = n / 16;
int d2 = n % 16;
return hexArray[d1] + hexArray[d2];
}
public static void main(String[] args) {
String password = StringDemo_26.createEncrypPassword("hahaxiao1984");
System.out.println("对password=hahaxiao1984使用MD5算法加密后的字符串如下:\n "
+ password);
String string = "hahaxiao1999";
System.out.println("hahaxiao1999是正确的密码吗?"
+ StringDemo_26.verificationPassword(password, string));
string = "hahaxiao1984";
System.out.println("hahaxiao1984是正确的密码吗?"
+ StringDemo_26.verificationPassword(password, string));
}
}
实例105 使用正则表达式验证电话号码的格式
package Chapter06.string;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringDemo_27 {
private static String REG_EXP = "^([0-9]{3}-?[0-9]{8})|([0-9]{4}-?[0-9]{7})$";
/** 使用String类中的matches方法利用正则表达式匹配的方法 */
public static boolean useMatches(String phoneNum) {
if (phoneNum != null) {
return phoneNum.matches(REG_EXP);
} else {
return false;
}
}
/** 使用Pattern的compile方法和Matcher的matcher方法共同匹配 */
public static boolean usePattern(String phoneNum) {
Pattern p = Pattern.compile(REG_EXP);
// 创建一个Matcher,并进行精确匹配
Matcher m = p.matcher(phoneNum);
return m.matches();
}
public static void main(String[] args) {
String phoneNum = "210-12345678";
System.out.println(phoneNum + " 是一个合法的电话号码格式吗? "
+ StringDemo_27.useMatches(phoneNum));
System.out.println(phoneNum + " 是一个合法的电话号码格式吗? "
+ StringDemo_27.usePattern(phoneNum));
phoneNum = "210-12345678";
System.out.println(phoneNum + " 是一个合法的电话号码格式吗? "
+ StringDemo_27.useMatches(phoneNum));
System.out.println(phoneNum + " 是一个合法的电话号码格式吗? "
+ StringDemo_27.usePattern(phoneNum));
phoneNum = "0439-1234567";
System.out.println(phoneNum + " 是一个合法的电话号码格式吗? "
+ StringDemo_27.useMatches(phoneNum));
System.out.println(phoneNum + " 是一个合法的电话号码格式吗? "
+ StringDemo_27.usePattern(phoneNum));
phoneNum = "010-88888888888";
System.out.println(phoneNum + " 是一个合法的电话号码格式吗? "
+ StringDemo_27.useMatches(phoneNum));
System.out.println(phoneNum + " 是一个合法的电话号码格式吗? "
+ StringDemo_27.usePattern(phoneNum));
phoneNum = "04ff-666ab##5";
System.out.println(phoneNum + " 是一个合法的电话号码格式吗? "
+ StringDemo_27.useMatches(phoneNum));
System.out.println(phoneNum + " 是一个合法的电话号码格式吗? "
+ StringDemo_27.usePattern(phoneNum));
}
}
本文概述了AI音视频处理领域的关键技术,包括视频分割、语义识别、自动驾驶、AR、SLAM、物体检测与识别、语音识别变声、终端AI边缘计算等,探讨了这些技术在实际应用中的价值与挑战。
892

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



