Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 977
Basant Kumar Avatar asked Jun 11 '16 10:06

Basant Kumar


People also ask

How do I split a string into two parts in C #?

In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.

How do I split a string into multiple strings?

split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings. We can also pass a limit to the number of elements in the returned array.

How do I split a string with one or more spaces?

To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.


3 Answers

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
like image 161
NValchev Avatar answered Oct 24 '22 00:10

NValchev


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
like image 40
Soner Gönül Avatar answered Oct 24 '22 00:10

Soner Gönül


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:

  • IndexOf
  • Substring
like image 3
Christos Avatar answered Oct 24 '22 01:10

Christos