我有一个字符串 = "google.com 220美元 3d 19h"。
我想提取".com"部分......
如何最简单地使用split字符串方法来获得此结果?
我有一个字符串 = "google.com 220美元 3d 19h"。
我想提取".com"部分......
如何最简单地使用split字符串方法来获得此结果?
我猜您要么想提取域名,要么想提取字符串中的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);
假设您想要顶级域名:
string str = "google.com 220 USD 3d 19h";
string tld = str.Substring(str.LastIndexOf('.')).Split(' ')[0];
Console.WriteLine(tld);
输出:
.com
这将考虑子域名。
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 );
如果你可以假设空格是分隔符,那么这就很容易了
string full
char[] delimiterChars = { ' ' }; // 用于指定更多的分隔符 string[] words = full.Split(delimiterChars, 1); // 只使用一个空格来分割单词
string result = words[0] // 这是如何访问它的方法
使用正则表达式是最好的选择,但如果您想使用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);
}
}