java 188 - 单词在句子中的位置

给定英文句子,编写方法void wordPositions(String sentence),该方法中计算sentence中的每个单词在句子中的起始位置和单词长度并输出。假设句子中只包含英文字母和空格,且单词不重复。
更新方法可以实现 查找重复单词出现的位置坐标 用正则的方法来统计第几次出现 
import java.util.Scanner;
import java.util.regex.*;;
public class Main {
	//子字符串modelStr在字符串str中第count次出现时的下标
	static int getFromIndex(String str, String modelStr, Integer count) {
		
	        Matcher slashMatcher = Pattern.compile(modelStr).matcher(str);
	        int index = 0;
			while(slashMatcher.find()) {
		    index++;
		    if(index == count){
		       break;
		    }
		}
	      	return slashMatcher.start();
	}
	static void wordPositions(String sentence) {
		
        String[] strings = sentence.split(" ");
        int[] num = new int[100];
        for(int i = 1;i < strings.length;i++) {
        	int cnt = 0;
        	for(int j = 0;j < i;j++) {
        		if(strings[i].equals(strings[j]))
        			cnt++;
        	}
        	num[i] = cnt+1;
        }
        num[0] = 1;
 
        int i = 0;
 
        while(i < strings.length) {
        	System.out.println(strings[i]+": "+getFromIndex(sentence,strings[i],num[i])+", "+strings[i].length());
 
            i++;
        }
 
     }

	public static void main(String[] args) {
		// TODO Auto-generated method stub

        Scanner s1 = new Scanner (System.in);
 
        String string = s1.nextLine();
 
        wordPositions(string);
 

	}

}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值