字符串习题小结
public class Test {
public static void main(String[] args) {
String str = "Nothing is impossible to a willing heart";
String str2 = "No cross, no crown.";
// 1, 打印整个str字符串去掉所有空格之后的长度
System.out.println(str.replace(" ", "").length());
// 2, 写代码找出字母"o","s"所在字符串str中第一次出现的索引位置, 找出字符串中最后一个"t"的索引位置, 并输出在控制台上
System.out.println(str.indexOf("o"));
System.out.println(str.indexOf("s"));
System.out.println(str.lastIndexOf("t"));
// 3, 写代码实现将str字符串用"空格"分割成数组, 并输出索引值为4的值
System.out.println(str.split(" ")[4]);
// 4, 写代码实现将str字符串中所有的"i"替换成"I"(禁用replace)
System.out.println(str.replace("i", "I"));
// 5, 编写代码从str字符串中取每个单词的首字母打印在控制台上
String[] strArray = str.split(" ");
for (int i = 0; i < strArray.length; i++) {
System.out.println(strArray[i].charAt(0));
}
// 6, 在不使用第三个变量的情况下互换str和str2的值
System.out.println("str=" + str);
System.out.println("str2=" + str2);
System.out.println("===================="); //将str和str2两个字符串应用字符串拼接的方法赋值到str里然后再用字符串截取的方法将str里的内容
str += str2; 赋值到str2里同理将str2里的内容赋值到str中如此一来便完成了str str2的互换
str2 = str.substring(0, str.length() - str2.length());
str = str.substring(str2.length());
System.out.println("str=" + str);
System.out.println("str2=" + str2);
// 1, 写一段代码, 可以取出任意qq邮箱地址中的qq号码
String qqcode = "78235687326458327@qq.com";
System.out.println(qqcode.substring(0, qqcode.indexOf("@")));运用字符串截取的方式进行抽取QQ号的操作.
System.out.println(qqcode.split("@")[0]);//运用分割字符串的方法用@将一整个字符分割成几个元素赋值到一个数组内此时在这个数组的索引值为0的元素即为QQ号
// 2, 使用for和if打印一个空心正方形
int n = 5;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == n - 1 || i == 0) {
System.out.print("* ");
} else {
if (j == 0 || j == n - 1) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
}
System.out.println();
}
// 3, 使用for循环打印一个菱形
int rows = 4;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3 - i; j++) {
System.out.print("0");
}
for (int k = 0; k < 2 * i + 1; k++) {
System.out.print("*");
}
System.out.println();
}
for (int i = 0; i < rows - 1; i++) {
for (int j = 0; j < i + 1; j++) {
System.out.print("0");
}
for (int k = 0; k < 5 - 2 * i; k++) {
System.out.print("*");
}
System.out.println();
}
以上的程序在经过编译运行之后便可以得到以下结果:


浙公网安备 33010602011771号