java查找字符位置_java 查找字符串所在的位置代码
时间: 2024-01-30 11:03:44 浏览: 20
以下是Java中查找字符串所在位置的代码示例:
```java
String mainStr = "Hello, world!";
String subStr = "world";
int index = mainStr.indexOf(subStr);
System.out.println("子字符串在主字符串中的位置为:" + index);
```
此代码中,我们使用`indexOf()`方法在主字符串中查找子字符串的位置。如果子字符串存在于主字符串中,则返回子字符串在主字符串中的起始索引;否则返回-1。以上代码输出结果为:
```
子字符串在主字符串中的位置为:7
```
相关问题
java查找字符串中指定字符的位置
可以使用 Java 中的 `indexOf()` 方法来查找字符串中指定字符的位置。例如,假设要查找字符 `'o'` 在字符串 `"Hello, world!"` 中的位置,可以使用以下代码:
```java
String str = "Hello, world!";
int index = str.indexOf('o');
System.out.println("Index of 'o': " + index);
```
输出结果为:
```
Index of 'o': 4
```
如果要查找字符串中所有指定字符的位置,可以使用类似以下代码:
```java
String str = "Hello, world!";
int index = str.indexOf('o');
while (index >= 0) {
System.out.println("Index of 'o': " + index);
index = str.indexOf('o', index + 1);
}
```
输出结果为:
```
Index of 'o': 4
Index of 'o': 7
```
java文件中查找字符串_Java 在本地文件中查找固定字符串
可以使用Java的IO流来读取本地文件,并使用字符串匹配函数来查找固定字符串。以下是一个示例代码:
```java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class SearchStringInFile {
public static void main(String[] args) {
String filePath = "path/to/your/file";
String searchString = "your search string";
File file = new File(filePath);
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
if (line.contains(searchString)) {
System.out.println("Found the string in the file: " + filePath);
break;
}
}
} catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
}
}
}
```
在上面的代码中,我们使用 `BufferedReader` 类从文件中读取数据,并使用 `contains` 函数来查找固定字符串。如果找到了该字符串,则在控制台输出相应的消息。请将 `filePath` 变量替换为您要搜索的文件的实际路径,并将 `searchString` 变量替换为您要查找的实际字符串。