Reputation: 13506
I have a string = "google.com 220 USD 3d 19h".
I want to extract just the ".com" part.......
whats the easiest way to manipulate the split string method to get this result?
Upvotes: 5
Views: 16229
Reputation: 351748
I cannot think of a reason in the world that you would want to use String.Split
for this purpose. This problem is best solved with a regular expression.
Here is a small program that demonstrates how to do it:
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);
}
}
Upvotes: 0
Reputation: 3235
Assuming you want the top-level domain:
string str = "google.com 220 USD 3d 19h";
string tld = str.Substring(str.LastIndexOf('.')).Split(' ')[0];
Console.WriteLine(tld);
Output:
.com
This takes subdomains into account.
Upvotes: 1
Reputation: 147461
I'm guessing you either want to extract the domain name or the TLD part of the string. This should do the job:
var str = "google.com 220 USD 3d 19h";
var domain = str.Split(' ')[0]; // google.com
var tld = domain.Substring(domain.IndexOf('.')) // .com
Upvotes: 8
Reputation: 32377
I know you asked about using the Split method but I'm not sure that's the best route. Splitting a string will allocate at least 5 new strings that are immediately ignored and then have to wait around until GC to be released. You're better off just using indexing into the string and pull out just what you need.
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 );
Upvotes: 1
Reputation: 9511
using Regex would be the best option but if you want to use Split then
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));
Upvotes: 0
Reputation: 17949
If by extract you mean remove, you can use the Replace method
var result = str.Replace(".com", "");
Upvotes: 1
Reputation: 4807
Alternate idea
string str = "google.com 220 USD 3d 19h";
string match = ".com";
string dotcomportion = str.Substring(str.IndexOf(match), match.Length);
Upvotes: 3
Reputation: 3590
well if you can assume that space is seperator its as easy as
string full
char[] delimiterChars = { ' ' }; // used so you can specify more delims string[] words = full.Split(delimiterChars, 1); // splits only one word with space
string result = words[0] // this is how you can access it
Upvotes: 1