华为机试题目学习心得
01字符串最后一个单词的长度
1. 题目思考
1.1例如like,是个单词,无空格,字符串长度为4;hello world是字符串,并且中间有空格,长度为11。那我如何获得最后一个单词长度?换句话讲怎么样读到最后一个单词的时候停下来,并且能计算出长度。如果顺序挨个读显然麻烦,那不妨直接从字符串末端读,当遇到最近的空格就停下来,在开始读和停下来得期间进行Count++即可,加几次长度就是几。如果是一个单词得情况,无法读到空格,你就需要if条件来跳出循环,先前要用gets函数获取整个字符串长度,这个时候你就可以直接输出gets获取得单词长度。(c语言实现)
1.2那Java中怎么去实现?Java对于字符串得实现有一些特别的函数,比如Lastindexof(),该函数括号中的参数可以是(int ch)、(int ch,fromIndex)、(string str)、(string str,fromIndex)。前两个函数是对char(字符)进行匹配,区别在于多了fromIndex,它的意思是从string中的第几位开始向前匹配。三四是对字符串进行匹配,(string str,fromIndex)声明开始向前匹配的位置。比如:hello world you are共计19个字符。而are是3,所以若用LastIndexof去匹配空格,它是由右往左匹配的,并且索引返回hello到are之前的空格所有字符数,这样用总字符数19-Lastindexof-1(索引从0开始)=最后一个字符串长度。
2. 代码编写
c编写
#include <stdio.h>
#include<string.h>
int main(){
char s[5001];
int sum=0;
gets(s);
int len=strlen(s);
for( int i=len-1;i>=0;i--){
if(s[i]==' ')
break;
sum++;
}
printf("%d",sum);
return 0;
}
Java编写
package 字符串最后一个单词的长度;
import java.util.Scanner;
public class Main {
public static void main (String[] args) {
Scanner in = new Scanner ( System.in );
String word = in.nextLine();
int n = word.lastIndexOf (" ");
if ( n == -1)
System.out.println( word.length() );
else {
String str = word.substring ( n ,word.length()-1 );
System.out.println(str.length());
}
}
}
3.学习总结
根据这道题目学习了indexof()和Lastindexof()方法,还有substring()函数。
package lastindexof测试;
public class Test {
public static void main(String[] args){
String str = “sdasaq”;
System.out.println(str.lastIndexOf(‘a’));//从右往左匹配,遇到第一个a返回a的索引值,索引是从左往右从0开始数。
System.out.println(str.lastIndexOf(‘a’,3));//从右往左匹配,索引(从左往右从0开始)第三个位置的字符即s处从右往左匹配到第一个a
System.out.println(str.lastIndexOf(“as”));//同理as也是从右往左匹配,匹配到第一个as后标号位置,从左往右索引该位置在输出索引结果即可
System.out.println(str.lastIndexOf(“as”,1));//从第一个字符(按照索引从左往右找)开始匹配,即从d开始右往左匹配发现不到匹配目标返回-1
//indexof是从左往右匹配的,索引也是从左往右从0开始的
System.out.println(str.indexOf('a') );
System.out.println(str.indexOf('a',3));
System.out.println(str.indexOf("as"));
System.out.println(str.indexOf("as",1));
System.out.println(str.substring(2));
System.out.println(str.substring(1,3));
//(1,3)中1是指索引为1的字符即d,3指长度,sd已经是长度为2了,但是截取位置是从d开始的,所以输出为da
// substring ()方法是字符串截取功能,里面参数可以是(int a,int b)
//int a 指的是开始截取位置,int b包含截取位置之前的字符长度和后面还需要的
}
//总结:indexof和lastIndexof都是返回一个位置,是个整数值,找不到返回-1;Indexof是从左向右查找(或叫匹配)
//LastIndexof是从右向左查,不管是它俩哪一个,索引序列都是从左向右从0开始
}