如何用indexOf()和substring()打印出字符串的第一个单词?

如题所述

indexOf(int ch)
返回指定字符在此字符串中第一次出现处的索引。

indexOf(String str)
返回指定子字符串在此字符串中第一次出现处的索引。

例如:String s = new String("write once, run anywhere!");
String ss = new String("run");
System.out.println("s.indexOf('r'): " + s.indexOf('r') );
System.out.println("s.indexOf(ss): " + s.indexOf(ss) );
结果为:s.indexOf('r'): 1

s.indexOf(ss): 12

2、例:我要截取第一个字符到第三个字符
String a="sdasdasd";
System.out.println(a.substring(0, 3));

输出结果:sda
温馨提示:答案为网友推荐,仅供参考
相似回答