在字符串中实现字符串的查找输出的代码
时间: 2024-05-14 15:16:46 浏览: 14
好的,以下是Python的示例代码:
```python
string = "Hello, world!"
substring = "world"
index = string.find(substring)
if index != -1:
print(f"Substring '{substring}' found at index {index} in string '{string}'")
else:
print(f"Substring '{substring}' not found in string '{string}'")
```
请问是否满意我的回答呢?
相关问题
java在字符串中实现子字符串的查找输出代码
可以通过使用 `indexOf()` 方法实现字符串中子字符串的查找。
以下是 Java 实现子字符串查找的示例代码:
```
String str = "Hello World";
String substr = "World";
int index = str.indexOf(substr);
if (index != -1) {
System.out.println(substr + " found at index " + index);
} else {
System.out.println(substr + " not found in string");
}
```
输出结果为:
```
World found at index 6
```
如果子字符串不存在于主字符串中,则 `indexOf()` 方法返回 -1。
在字符串中实现字符串的查找输出的代码用java
可以使用 Java 中的 String 类的 indexOf() 方法进行字符串查找。以下是一个简单的示例程序:
```java
public class FindString {
public static void main(String[] args) {
// 定义一个字符串
String str = "Hello, world!";
// 查找字符串中是否包含子字符串 "world"
int index = str.indexOf("world");
if (index >= 0) {
// 找到了,输出结果
System.out.println("Substring found at index " + index);
// 输出子字符串
System.out.println("Substring is: " + str.substring(index, index + 5));
} else {
// 没找到
System.out.println("Substring not found");
}
}
}
```
这段程序会在字符串 "Hello, world!" 中查找子字符串 "world",如果找到了就输出子字符串的位置和内容。如果没有找到,就输出 "Substring not found"。注意,indexOf() 方法返回的是子字符串出现的位置,如果找不到会返回 -1。substring() 方法用于获取子字符串,它接受两个参数,第一个参数是子字符串的起始位置,第二个参数是子字符串的长度。