1:字符串最后一个单词的长度
static void test0(){ Scanner sc = new Scanner(System.in); String str = sc.nextLine(); int length = str.length(); int count = 0; for (int i = length - 1; i >= 0; i--) { if (str.charAt(i)==' ') { // 或者 if (str.substring(i, i + 1).equals(" ")) { break; } count++; } System.out.println(count); }
public static void main(String[] args){ Scanner sc = new Scanner(System.in); String str = sc.nextLine(); String[] s = str.split(" "); //正则表达式实用性更强( str.split("\s+")) int length = s[s.length - 1].length(); System.out.println(length); }
评:简单,二解的性能较高
2:计算某字符出现次数
public static void test1(String[] args){ Scanner input = new Scanner(System.in); // 完整字符串 String str1 = input.nextLine().toLowerCase(); // 单个字符串 String str2 = input.nextLine().toLowerCase(); // 完整字符的长度-单个字符长度 = 出现的次数 int num = str1.length() - str1.replaceAll(str2,"").length(); System.out.println(num); }
评:简单,如果陷入传统思维则非常不好解且容易出错,以上的以第一个是总长度减去第二单字符在第一个总长度中替换的剩余长度的解法简单又不会出问题。
3:字符串分隔
static void test2(){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String str = sc.nextLine(); StringBuilder sb = new StringBuilder();//牢记字符串缓冲区的建立语法 sb.append(str);//字符串缓冲区的加入 int size = str.length(); int addZero = 8 - size%8;//addzero的可能值包括8 while((addZero > 0)&&(addZero<8)){//注意边界调节,避免addzero=8 sb.append("0");//使用‘’或“”都可 addZero--; } String str1 = sb.toString(); while(str1.length()>0){ System.out.println(str1.substring(0,8)); str1 = str1.substring(8); } }
评:简单,依然是减法补位,输出时候注意字符终止末位更新
4:字符个数统计
import java.util.Scanner;
import java.util.BitSet;public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String line = scanner.next();
//总共有128个字符。字需要用128位
BitSet bitSet = new BitSet(128);
for (char c : line.toCharArray()) {
//判断字符c是否已出现
if (!bitSet.get(c)) {
//未出现就设置为已出现
bitSet.set(c);
}
}
//统计有多少字符已出现过
System.out.println(bitSet.cardinality());
}
}
评:凡是涉及到去重统计都可以用位图实现。因为每一个不同的数据只需要用二进制的一位存储即可,大大减小了统计所使用的存储空间
5:字符串反转
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
StringBuffer strb = new StringBuffer(str);
strb.reverse();
System.out.println(strb.toString());
}
}
6:句子逆序
//描述 //将一个英文语句以单词为单位逆序排放。例如“I am a boy”,逆序排放后为“boy a am I” //所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符 // //数据范围:输入的字符串长度满足 // //注意本题有多组输入 //输入描述: //输入一个英文语句,每个单词用空格隔开。保证输入只包含空格和字母。 // //输出描述: //得到逆序的句子 static void test5( ) { Scanner sc = new Scanner(System.in); String line = sc.nextLine(); String[] array = line.split(" "); for (int i = array.length - 1; i >= 0; i--) { System.out.print(array[i]+" "); } }