要获取文本中特定内容的开始和结束索引,可以使用多种编程语言中的字符串处理功能。以下是一些常见编程语言中的示例代码:
text = "Hello, world!"
substring = "world"
start_index = text.find(substring)
end_index = start_index + len(substring) - 1 if start_index != -1 else -1
print(f"Start index: {start_index}, End index: {end_index}")
const text = "Hello, world!";
const substring = "world";
const start_index = text.indexOf(substring);
const end_index = start_index + substring.length - 1;
console.log(`Start index: ${start_index}, End index: ${end_index}`);
public class Main {
public static void main(String[] args) {
String text = "Hello, world!";
String substring = "world";
int start_index = text.indexOf(substring);
int end_index = start_index + substring.length() - 1;
System.out.println("Start index: " + start_index + ", End index: " + end_index);
}
}
using System;
class Program {
static void Main() {
string text = "Hello, world!";
string substring = "world";
int start_index = text.IndexOf(substring);
int end_index = start_index + substring.Length - 1;
Console.WriteLine("Start index: " + start_index + ", End index: " + end_index);
}
}
find
或 indexOf
方法返回 -1
。-1
,以避免数组越界错误。通过这些方法和技巧,可以有效地获取文本中特定内容的开始和结束索引。
企业创新在线学堂
技术创作101训练营
小程序·云开发官方直播课(数据库方向)
Elastic 中国开发者大会
Elastic Meetup
Elastic 实战工作坊
Elastic 实战工作坊
TVP技术夜未眠
领取专属 10元无门槛券
手把手带您无忧上云