簡體   English   中英

C#字符串拆分

[英]C# string split

我有一個字符串=“google.com 220 USD 3d 19h”。

我想提取“.com”部分.......

什么是最簡單的方法來操縱split string方法來獲得這個結果?

我猜你要么提取字符串的域名或TLD部分。 這應該做的工作:

var str = "google.com 220 USD 3d 19h";
var domain = str.Split(' ')[0];           // google.com
var tld = domain.Substring(domain.IndexOf('.')) // .com

替代的想法

string str = "google.com 220 USD 3d 19h";
string match = ".com";
string dotcomportion = str.Substring(str.IndexOf(match), match.Length);

好吧,如果你可以假設空間是分離器就像它一樣容易

滿滿的

char [] delimiterChars = {''}; //使用所以你可以指定更多delims string [] words = full.Split(delimiterChars,1); //只用空格分割一個單詞

string result = words [0] //這是你可以訪問它的方法

假設你想要頂級域名:

string str = "google.com 220 USD 3d 19h";
string tld = str.Substring(str.LastIndexOf('.')).Split(' ')[0];
Console.WriteLine(tld);

輸出:

.com

這會考慮子域。

如果通過提取意味着刪除,則可以使用Replace方法

var result = str.Replace(“。com”,“”);

我知道你問過使用Split方法,但我不確定這是最好的路線。 拆分字符串將分配至少5個立即被忽略的新字符串,然后必須等待,直到GC被釋放。 你最好只使用索引到字符串中,然后拉出你需要的東西。

string str =  "google.com 220 USD 3d 19h";
int ix = str.IndexOf( ' ' );
int ix2 = str.IndexOf( '.', 0, ix );
string tld = str.Substring( ix2, ix - ix2 );
string domain = str.Substring( 0, ix );

使用Regex將是最好的選擇,但如果你想使用Split那么

  var str = "google.com 220 USD 3d 19h";
        var str1  = str.Split(' ')[0];
        var str2 = str1.Split('.')[0];
        Console.WriteLine(str1.Replace(str2, string.Empty));

我想不出世界上你想要將String.Split用於此目的的原因。 使用正則表達式可以最好地解決此問題。

這是一個小程序,演示了如何執行此操作:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        String foo = "google.com 220 USD 3d 19h";
        Regex regex = new Regex(@"(.com)", RegexOptions.IgnoreCase);
        Match match = regex.Match(foo);

        if (match.Success)
            Console.WriteLine(match.Groups[1].Value);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM