- Home /
Split String into Arrays
Hello,
I have a string like this:
00-tweets/Username
I want to somehow split the string, and place different parts of the string into arrays. The format is as follows:
[Index] -tweets/ [Username]
I want the 'Index', which is '00' to be inserted into one array, and the 'Username' to be interested into another, whilst the '-tweets/' is completely ignored/removed. This is essentially what breaks the Index apart from the Username.
Thanks
Answer by $$anonymous$$ · May 18, 2015 at 03:10 PM
If you know that the tweets section cannot contain any forward slashes then you can use a function to get the string before the first hyphen (a.k.a the index) and then use another function to get the string after the forwards slash (a.k.a the username).
The actual functions (which I've taken from my library of helper functions):
/// <summary>
/// Returns the substring before the given value.
/// If the value is not found in the string then the default value is returned.
/// </summary>
/// <param name="value">The value to search for</param>
/// <param name="defaultValue">The value to return if the string was not found</param>
/// <param name="caseSensitive">If true the search is case sensistive. Optional.</param>
public static string SubstringBefore(this string str, string value, string defaultValue, bool caseSensitive = false)
{
// If the string is not null or empty
if (!str.IsNullOrEmpty())
{
// The index of the value found
int index = -1;
if (caseSensitive)
{
// Case sensitive so don't do anything extra
index = str.IndexOf(value);
}
else
{
// Case insensitive, so lowercase both first
index = str.ToLowerInvariant().IndexOf(value.ToLowerInvariant());
}
// If we found something
if (index >= 0)
{
// Return everything before that index
return str.Substring(0, index);
}
}
// Default to the default value
return defaultValue;
}
/// <summary>
/// Returns the substring after the given value.
/// If the value is not found in the string then the default value is returned.
/// </summary>
/// <param name="value">The value to search for</param>
/// <param name="defaultValue">The value to return if the string was not found</param>
/// <param name="caseSensitive">If true the search is case sensistive. Optional.</param>
public static string SubstringAfter(this string str, string value, string defaultValue, bool caseSensitive = false)
{
// If the string is not null or empty
if (!str.IsNullOrEmpty())
{
// The index of the value found
int index = -1;
if (caseSensitive)
{
// Case sensitive so don't do anything extra
index = str.IndexOf(value);
}
else
{
// Case insensitive, so lowercase both first
index = str.ToLowerInvariant().IndexOf(value.ToLowerInvariant());
}
// If we found something
if (index >= 0)
{
// Return everything after that index
return str.Substring(index + value.Length);
}
}
// Default to the default value
return defaultValue;
}