溫馨提示×

c#字符串怎么提取

c#
小億
176
2024-10-27 00:08:31
欄目: 編程語言

在C#中,可以使用以下幾種方法來提取字符串中的子字符串:

  1. 使用Substring方法:
string str = "Hello, World!";
string subStr = str.Substring(0, 5); // 提取從索引0開始,長度為5的子字符串
Console.WriteLine(subStr); // 輸出:Hello
  1. 使用IndexOfSubstring方法結合:
string str = "Hello, World!";
int index = str.IndexOf("World"); // 查找子字符串"World"的索引
string subStr = str.Substring(index, "World".Length); // 提取從索引index開始,長度為"World".Length的子字符串
Console.WriteLine(subStr); // 輸出:World
  1. 使用正則表達式(Regex):
using System.Text.RegularExpressions;

string str = "Hello, [World!]";
Match match = Regex.Match(str, @"\[(.*?)\]"); // 使用正則表達式匹配方括號內的內容
if (match.Success)
{
    string subStr = match.Groups[1].Value; // 提取匹配到的子字符串
    Console.WriteLine(subStr); // 輸出:World
}

根據你的需求,可以選擇合適的方法來提取字符串中的子字符串。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女