如何使用substring截取字符串

小樊
84
2024-08-29 08:16:55
欄目: 編程語言

在許多編程語言中,substring 方法或函數(shù)用于從一個(gè)給定的字符串中提取一部分字符

  1. Python:
string = "Hello, World!"
start_index = 0
end_index = 5
sub_string = string[start_index:end_index]
print(sub_string)  # 輸出 "Hello"
  1. JavaScript:
let string = "Hello, World!";
let startIndex = 0;
let endIndex = 5;
let subString = string.substring(startIndex, endIndex);
console.log(subString);  // 輸出 "Hello"
  1. Java:
public class Main {
    public static void main(String[] args) {
        String string = "Hello, World!";
        int startIndex = 0;
        int endIndex = 5;
        String subString = string.substring(startIndex, endIndex);
        System.out.println(subString);  // 輸出 "Hello"
    }
}
  1. C#:
using System;

class Program {
    static void Main() {
        string str = "Hello, World!";
        int startIndex = 0;
        int length = 5;
        string subStr = str.Substring(startIndex, length);
        Console.WriteLine(subStr);  // 輸出 "Hello"
    }
}

注意:不同編程語言中 substring 方法的參數(shù)和行為可能略有不同。請(qǐng)根據(jù)所使用的編程語言查閱相應(yīng)文檔。

0