cesolution
cesolution

Reputation: 31

I'd like to divide the strings to two array

I have a string data like "aaa.bbb.ccc" or "aaa.bbb.ccc.ddd". If I split this like "aaa.bbb.ccc".split("."), it becomes "aaa", "bbb" and "ccc". I want to divide this to just two strings like "aaa", "bbb.ccc". I think I can do this by firstly dividing everything and rejoining it but it's not smart way. Is there any way to set this more smoothly?

Upvotes: 0

Views: 66

Answers (3)

Dai
Dai

Reputation: 155250

If you want to split on the first dot character, use Substring:

String value = "aaa.bbb.ccc";
Int32 firstDotIdx = value.IndexOf( '.' );
if( firstDotIdx > -1 ) {
    return new String[] {
        value.Substring( 0, firstDotIdx ),
        value.Substring( firstDotIdx + 1 );
    }
} else {
    return new String[] {
        value,
        "";
    }
}
  • If you have "aaa.bbb" then it will return { "aaa", "bbb" }.
  • If you have "aaa.bbb.ccc" then it will return { "aaa", "bbb.ccc" }.
  • If you have ".aaa.bbb" then it will return { "", "aaa.bbb" }.
  • If you have "aaa" then it will return { "aaa", "" }.

Upvotes: 3

Zoltán Tamási
Zoltán Tamási

Reputation: 12764

I have a bunch of extension methods for these kind of string manipulations. An example usage for your task would look like this.

var str = "aaa.bbb.ccc.ddd";
var result = new[] { str.TakeUntil("."), str.TakeFrom(".") }; 

And the extension pack looks like this. The functions` results will not include the search string itself, and if the search string is not present in the input, they will return the whole input as result (this is a convention which suites my needs for this edge case, could be changed).

public static string TakeUntil(this string s, string search)
{
    if (string.IsNullOrEmpty(s)) return s;
    var pos = s.IndexOf(search, StringComparison.OrdinalIgnoreCase);
    if (pos >= 0)
        return s.Substring(0, pos);
    return s;
}
public static string TakeUntilLast(this string s, string search)
{
    if (string.IsNullOrEmpty(s)) return s;
    var pos = s.LastIndexOf(search, StringComparison.OrdinalIgnoreCase);
    if (pos >= 0)
        return s.Substring(0, pos);
    return s;
}

public static string TakeFrom(this string s, string search)
{
    if (string.IsNullOrEmpty(s)) return s;
    var pos = s.IndexOf(search, StringComparison.OrdinalIgnoreCase);
    if (pos >= 0)
        return s.Substring(pos + search.Length);
    return s;
}
public static string TakeFromLast(this string s, string search)
{
    if (string.IsNullOrEmpty(s)) return s;
    var pos = s.LastIndexOf(search, StringComparison.OrdinalIgnoreCase);
    if (pos >= 0)
        return s.Substring(pos + search.Length);
    return s;
}

Upvotes: 0

user6767845
user6767845

Reputation:

You can set the number of splitted parts:

string myString = "aaa.bbb.ccc";
int parts = 2;
string[] myParts = myString.Split(new string[] {"."}, parts, StringSplitOptions.None);

Upvotes: 4

Related Questions