Basant Kumar
Basant Kumar

Reputation: 227

Split string at first space and get 2 sub strings in c#

I have a string like this

INIXA4 Agartala
INAGX4 Agatti Island

I want to split such a way that it will be like INAGX4 & Agatti Island

If I am using var commands = line.Split(' ');

It splits like INAGX4, Agatti, Island

If there is 4 space it give 4 array of data.How can I achieve only 2 substring

Upvotes: 20

Views: 37753

Answers (4)

NValchev
NValchev

Reputation: 3005

You can just use

string.Split(char separator, int count, StringSplitOptions options = System.StringSplitOptions.None)

overload of string object and pass 2 as count where it is "The maximum number of substrings to return." Here is an example:

var input = "INAGX4 Agatti Island";
var splitted = input.Split(' ', 2);
Console.WriteLine(splitted[0]); // INAGX4
Console.WriteLine(splitted[1]); // Agatti Island

Upvotes: 46

Christos
Christos

Reputation: 53958

You could try something like this, using the IndexOf and Substring methods of string:

var str = "INAGX4 Agatti Island";
var indexOfFirstSpace = str.IndexOf(" ");
var first = str.Substring(0, indexOfFirstSpace);
var second = str.Substring(indexOfFirstSpace+1);

For a detailed documentation about the above methods, please have a look at the following links:

Upvotes: 3

Soner Gönül
Soner Gönül

Reputation: 98740

Since you have 2 space, Split(' ') generates an array with 3 elements.

Based on your example, you can get the index of your first white space and generate your strings with Substring based on that index.

var s = "INAGX4 Agatti Island";
var firstSpaceIndex = s.IndexOf(" ");
var firstString = s.Substring(0, firstSpaceIndex); // INAGX4
var secondString = s.Substring(firstSpaceIndex + 1); // Agatti Island

Upvotes: 25

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14604

Try this

string str = "INAGX4 Agatti Island";
string firstStinrg = str.Substring(0, str.IndexOf(' '));
string secondsStrig = str.Substring(str.IndexOf(' ')+1);

Upvotes: 1

Related Questions