1.常用字符串方法
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String msg="hello world hello kitty";
System.out.println(msg.length());//得字符串长度
String[] arr=msg.split(" ");//分词
System.out.println(Arrays.toString(arr));
//23
//[hello, world, hello, kitty]
String new_msg=msg.replace("hello","你好");//替换
System.out.println(new_msg);
//你好 world 你好 kitty
String sub_str=msg.substring(1,9);
System.out.println(sub_str);//提取
//ello wor
int idx=msg.indexOf("hello");//查询是否包含,并返回下标
int idx1=msg.lastIndexOf("hello");//从后往前查
System.out.println(idx);
System.out.println(idx1);
// 0
// 12
char[] char_arr=msg.toCharArray();//转换为字符数组
for(char c:char_arr){
System.out.println(c);
}
System.out.println(char_arr[2]);
//l
System.out.println(msg.charAt(2));//返回该下标的内容,和上述代码一样效果
//l
String info=new String("xxxxx");
String info1=new String("xxxxx");
if (info1==info){//判断两个地址是否相等
System.out.println("====");
}
else {
System.out.println("!===");
}
if (info1.equals(info)){//判断两个内容是否相等
System.out.println("====");
}
else {
System.out.println("!===");
}
//!===
//====
}
}
2.猜单词游戏
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class GuessWord {
public static void main(String[] args) {
String sentence="static class extend interface replace apple banana";
String[] words=sentence.split(" ");
Random random=new Random();
int random_idx= random.nextInt(words.length);
String select_word=words[random_idx];
//System.out.println(select_word);//随机出单词
char[] word_arr=new char[select_word.length()];
Arrays.fill(word_arr,'-');
//System.out.println(word_arr);//填充“-”
int guess_time=5;
while (guess_time>0){
System.out.println(word_arr);
System.out.println("你还有"+guess_time+"次机会");
System.out.println("请输入猜测字母:");
Scanner scanner=new Scanner(System.in);
char guess_char=scanner.nextLine().charAt(0);
if (select_word.contains(String.copyValueOf(new char[]{guess_char}))){
for (int i=0;i<select_word.length();i++){
if (select_word.charAt(i)==guess_char){
word_arr[i]=guess_char;
}
}
int i=0;
for (;i<word_arr.length;i++){
if (word_arr[i]=='-'){
break;
}
}
if (i==word_arr.length){
break;
}
}
else {
guess_time--;
}
}
if (guess_time>0){
System.out.println("you win");
}else {
System.out.println("you lose");
}
}
}