1. 计算字符串最后一个单词的长度,单词以空格隔开。
1.1 分析
两个指针:pre和post。用于确定最后一个单词的前后位置
当pre位置的字符为空格时,post置为它的下一位,post自增,知道它等于数组长度(遍历结束)或者它当前所指位置为空格;
- 若为空格,则令pre=post,post=pre+1重复上述步骤
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
new Main().getNum(str);
}
public void getNum(String str) {
int pre=0;
int post=0;
if(str.indexOf(' ')==-1){
System.out.println(str.length());
return;
}
char[] chs=str.toCharArray();
while(pre<chs.length) {
if(chs[pre]==' ') {
post=pre+1;
while(post<chs.length&&chs[post]!=' ')
post++;