JAVA之定位字符串

来源:互联网 发布:如何申请网络域名 编辑:程序博客网 时间:2024/05/20 20:01
1、JAVA之定位字符串 。
打开记事本,写如下一段代码:
import java.util.Scanner;/** * 字符串查找  * */public class StringExplorer{/** * 定位字符 */public void locateChar(String full, char c) {System.out.print(c + "出现的位置是: ");for (int i = 0; i < full.length(); i++) {if (c == full.charAt(i)) {System.out.print(i + "\t");}}}/** * 定位字符串 */public void locateString(String full, String s) {int index = 0;int i = index;int length = full.length();System.out.print(s + "出现的位置是: ");do {index = full.indexOf(s, i);if (index == -1) {break;}System.out.print(index + "   ");i = index + s.length();} while (i <= length);}public static void main(String[] args) {StringExplorer se = new StringExplorer();Scanner input = new Scanner(System.in);System.out.println("请输入一段字符: ");String full = input.next();System.out.println("请输入要查询的字符串: ");String s = input.next();se.locateString(full, s);}}
保存为StringExplorer.java【同上节,我还是把他放在了D盘下InputTest文件夹内】 
打开dos运行窗口,输入d:转到D盘,接下来输入cd InputTest转到InputTest目录下:
输入Javac StringExplorer.java 回车 java StringExplorer。结果如下图:  

我们输入一段话:这是为什么呢? 我们查找 “ 为” 这个字符。结果如下:


1 0