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
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.
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.
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.
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
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
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With