Topic: Calculate the length of the last word of a string
Description
Calculate the length of the last word of a string, words are separated by spaces, and the length of the string is less than 5000.
(Note: The end of the string does not end with a space)
Input description:
Enter a line, representing the string to be calculated, non-empty, and the length is less than 5000.
Output description:
Output an integer representing the length of the last word of the input string.
Example:
输入:hello nowcoder
输出:8
说明:最后一个单词为nowcoder,长度为8
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
//BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
//bf.readLine();
//Scanner sc = new Scanner(System.in);
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String[] strs = s.split(" ");
System.out.println(strs[strs.length-1].length());
}
}
Question: Count the number of occurrences of a letter
Description
Write a program that takes a string of letters, numbers, and spaces, and a letter, and outputs the number of occurrences of that letter in the input string. (case insensitive letters)
Data range: , the input data may contain uppercase and lowercase letters, numbers and spaces.
Input description:
input a string consisting of letters, numbers and spaces in the first line, and input a letter in the second line.
Output description:
Output the number of characters contained in the input string.
输入:ABCabc
A
输出:2
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String c = sc.next();
char[] chars1 = s.toLowerCase().toCharArray();
char[] chars2 = c.toLowerCase().toCharArray();
int count = 0;
for (char c1 : chars1) {
if (c1 == chars2[0]){
count++;
}
}
System.out.println(count);
}
}
String's toLowerCase() method converts all letters in the string to lowercase