利用java实现找到英语单词在一句话中的位置
时间: 2023-05-23 11:04:14 浏览: 52
A:可以通过使用String类的indexOf方法来查找单词在一句话中的位置。
以下是Java代码示例:
```java
public class WordPositionFinder {
public static void main(String[] args) {
String sentence = "Hello world! This is an example sentence.";
String word = "example";
int position = sentence.indexOf(word);
if(position >= 0) {
System.out.println("The word '" + word + "' starts at position " + position + " in the sentence: " + sentence);
} else {
System.out.println("The word '" + word + "' is not found in the sentence: " + sentence);
}
}
}
```
这个程序将输出:
```
The word 'example' starts at position 24 in the sentence: Hello world! This is an example sentence.
```
如果单词没有在句子中找到,则程序将输出:
```
The word 'example' is not found in the sentence: Hello world! This is an example sentence.
```