简体   繁体   中英

How can I split a string using the number of characters from the beginning of the string?

How can I split a string using the number of characters from the beginning of the string?

Here is my code:

string website;

if (message.Contains("!help"))
{
    SendChatMessage("\n!resolve <url> - Resolve a website URL\n!spam <steamID> <message> - Spam a steam user\n!help - View commands list");
}
else if (message.Contains("!resolve"))
{
    website = message;
    SendChatMessage(website);
    SendChatMessage("Resolving...");
    SendChatMessage("I couldn't resolve that IP address! Sorry!");
}

It's messy and formatted badly granted, but I am new to C# and I was wondering if there is any way I can split the website string using the knowledge that the initial 8 characters will be: "!resolve" After this there will be a website url.

Using Substring is the quickest and easiest way.

var text = "!resolve http://www.google.com";
var url = text.Substring(8).Trim();

The first parameter of Substring is the zero-based index into the string you want to start copying from. If you only specify that parameter, it will copy all of the text in the string starting from that index into a new string.

Split is based on characters or strings. If you want to split on position, you want substring: https://msdn.microsoft.com/en-us/library/system.string.substring%28v=vs.110%29.aspx

dotnetperls has a more user-friendly explanation: http://www.dotnetperls.com/substring

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM