C# How to split a string by space into few arrays [duplicate] - c#

This question already has answers here:
Text Split with Space
(2 answers)
Closed 5 years ago.
So I have a string input like this:
string pianist = "Johann Sebastian Bach";
How to split those by space so I can access such as:
pianist[0] == "Johann"
pianist[1] == "Sebastian"
pianist[2] == "Bach"
I tried
string test = pianist.Split(' ');
but its not working.

you can try this one;
string[] pianist = "Johann Sebastian Bach".Split(' ');
you will get as expected.

string test = pianist.Split(' '); // Doesn't work Why?
Because the .Split() method of String class Splits a string into substrings that are based on the characters in an array. you cannot assign them to a string, you should use an array instead.
What to do to make your code work?
Change the type of to string[] to hold the result of split:
string[] splitResult = pianist.Split(' ');

The problem is that your expectation is wrong.
so I can access such as pianist[0] == "Johann"
since pianist is your original string, trying to access it with an index will result in chars at this position in the string. (since a string is represented by a char[]).
If you look at the documentation of the method Split() you will see that it returns a string[] and not a string as you tried. You need first to catch this return value in an extra variable, then you can access it the way you planed:
string pianist = "Johann Sebastian Bach";
string [] returnedArray = pianist.Split(' ');
string johann = returnedArray[0];
string sabastian = returnedArray[1];
string bach = returnedArray[2];

You don't need to pass any params of your split method. check interested MSDN post:
If the separator argument is null or contains
no characters, the method treats white-space characters as the
delimiters. White-space characters are defined by the Unicode
standard they return true if they are passed to the Char.IsWhiteSpace
method.
String.Split Method
string pianist = "Johann Sebastian Bach";
var pianistArray = pianist.Split();
Result:
pianistArray[0] == "Johann"
pianistArray[1] == "Sebastian"
pianistArray[2] == "Bach

You are trying to save a string-array under a string variable. Try this:
string test = "Johann Sebastian Bach";
string[] separated = test.Split(' ');
foreach(string sub in separated)
{
Console.WriteLine(sub);
}
produces
Johann
Sebastian
Bach

Split function must specify the value to split. your situation is a space " ", not "".
here is the answer
string pianist = "Johann Sebastian Bach";
string[] asd = pianist.Split(" ");

It should see below looks like you have not given the space correctly
var res = pianist.Split(new[] {' '});

string test = pianist.Split(' ');
This won't work as the result from Split is an array. Do this instead:
string[] test = pianist.Split(' ');
No you can access the words like you already tried to:
test[0]
test[1]
...

Try this:
string pianist = "Johann Sebastian Bach";
var result = pianist.Split(' ');
Or:
string pianist = "Johann Sebastian Bach";
string[] result = pianist.Split(' ');

Related

Separate a string and place in array

How can I split this string and place in into an array can it be by a break line or new lines
This is the api url
https://stats.nba.com/stats/draftcombinenonstationaryshooting https://stats.nba.com/stats/draftcombinenonstationaryshooting https://stats.nba.com/stats/boxscoreplayertrackv2
I tried using but the string place it in index 0
string[] lines = split.Split(
new[] { Environment.NewLine },
StringSplitOptions.None
);
I would like to get each individual link from the string and store in an array
Source link: any-api.com
You can also call Split() without any arguments, in which case it will split on whitespace characters, so your sample code can simply be reduced to:
string[] lines = split.Split();
var array = urlString.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
This ensures there are no blank elements in array if URLs are separated by multiple spaces.
Here is a demo for you, you can try it.
string urlString = "https://stats.nba.com/stats/draftcombinenonstationaryshooting https://stats.nba.com/stats/draftcombinenonstationaryshooting https://stats.nba.com/stats/boxscoreplayertrackv2";
var array = urlString.Split(' ');
In your case, you can easily use the Regex like this:
string data = " https://stats.nba.com/stats/draftcombinenonstationaryshooting https://stats.nba.com/stats/draftcombinenonstationaryshooting https://stats.nba.com/stats/boxscoreplayertrackv2";
string regex = #"\s";
string[] result = Regex.Split(data.Trim(), regex);

How can I find a string between repeated strings in C#?

How can I find a string between repeated strings?
For example, if
string str = #"||AAA||BBB||CCC||";
how can I find all the strings(AAA, BBB, CCC) in order between repeated strings(||)?
Just use String.Split:
var str = #"||AAA||BBB||CCC||";
var splits = str.Split(new string[] {"||"}, StringSplitOptions.RemoveEmptyEntries);

Split string and get Second value only

I wonder if it's possible to use split to divide a string with several parts that are separated with a comma, like this:
10,12-JUL-16,11,0
I just want the Second part, the 12-JUL-16 of string and not the rest?
Yes:
var result = str.Split(',')[1];
OR:
var result = str.Split(',').Skip(1).FirstOrDefault();
OR (Better performance - takes only first three portions of the split):
var result = str.Split(new []{ ',' }, 3).Skip(1).FirstOrDefault();
Use LINQ's Skip() and First() or FirstOrDefault() if you are not sure there is a second item:
string s = "10,12-JUL-16,11,0";
string second = s.Split(',').Skip(1).First();
Or if you are absolutely sure there is a second item, you could use the array accessor:
string second = s.Split(',')[1];
Yes, you can:
string[] parts = str.Split(',');
Then your second part is in parts[1].
or:
string secondPart = str.Split(',')[1];
or with Linq:
string secondPart = str.Split(',').Skip(1).FirstOrDefault();
if (secondPart != null)
{
...
}
else
{
...
}
Also you can use not only one symbol for string splitting, i.e.:
string secondPart = str.Split(new[] {',', '.', ';'})[1];
You could use String.Split, it has an overloaded method which accepts max no of splits.
var input = "10,12-JUL-16,11,0"; // input string.
input.Split(new char[]{','},3)[1]
Check the Demo
Here's a way though the rest have already mentioned it.
string input = "10,12-JUL-16,11,0";
string[] parts = input.Split(',');
Console.WriteLine(parts[1]);
Output:
12-JUL-16
Demo

Not Trimming white spaces from a string in c#

Trim() Function Not Working Please Help its not trimming the white space.
string samplestring = "172-6573-4955";
string[] array = samplestring .Split('-');
string firstElem = array.First();
string restOfArray = string.Join(" ", array.Skip(1));
array[1] = restOfArray.Trim(); // providing value "6573 4955"
The scenario is I am splitting string and merging 2nd and last index into one but it's merging with white spaces.
Trim() removes whitespace from the front and back of a string, not in the middle. The whitespaces in the middle are being inserted by the " " provided as the parameter to Join() method. You could provide string.empty instead.
Trim is used to remove all leading and trailing white-space. And you want to trim the white space from middle. You may try like this:
string restOfArray = string.Join("", array.Skip(1));
or better:
string restOfArray = string.Join(string.Empty, array.Skip(1));
instead of
string restOfArray = string.Join(" ", array.Skip(1));
Trim is working as expected. Taken from String.Trim Method:
Removes all leading and trailing white-space characters from the
current String object.
The possible solutions for you are :
string restOfArray = string.Join(string.Empty, array.Skip(1));
Or
array[1] = restOfArray.Replace(" ", string.Empty).Trim();
To just split the first n-let from the rest use an additional array or you will end up with spurious data. And join with the correct separator you used in split(-):
string restOfArray = string.Join("-", array.Skip(1));
string[] result = new string[] { firstElem, restOfArray };
You don't need Trim().
You can simplify your code this way:
string[] splitCode(string code)
{
string[] segments;
segments = code.Split('-');
return new string[] { segments.First(), string.Join("-", segments.Skip(1)) };
}
Trim really isn't need here; you can simply split the string and join the parts you want:
string source = "172-6573-4955";
string[] splitter = new string[] {"-"};
string[] result;
result = source.Split(splitter, StringSplitOptions.None);
string final = (result[1] + result[2]);
Console.Write(final);
Result:
65734955
Try this:
string samplestring = "172-6573-4955";
string[] array = samplestring.Split(new char[] {'-'},2);
string result = array[1].Replace("-","");
Also, for your question about randomly putting spaces, can u pls explain "randomly" here.

split string after comma and till string ends- asp.net c#

I have a string of type
ishan,training
I want to split the string after "," i.e i want the output as
training
NOTE: "," does not have a fixed index as the string value before "," is different at different times.
e.g ishant,marcela OR ishu,ponda OR amnarayan,mapusa etc...
From all the above strings i just need the part after ","
You can use String.Split:
string[] tokens = str.Split(',');
string last = tokens[tokens.Length - 1]
Or, a little simpler:
string last = str.Substring(str.LastIndexOf(',') + 1);
var arr = string.Split(",");
var result = arr[arr.length-1];
sourcestring.Substring(sourcestring.IndexOf(',')). You might want to check sourcestring.IndexOf(',') for -1 for strings without ,.
I know this question has already been answered, but you can use linq:
string str = "1,2,3,4,5";
str.Split(',').LastOrDefault();
Although there are several comments mentioning the issue of multiple commas being found, there doesn't seem to be any mention of the solution for that:
string input = "1,2,3,4,5";
if (input.IndexOf(',') > 0)
{
string afterFirstComma = input.Split(new char[] { ',' }, 2)[1];
}
This will make afterFirstComma equal to "2,3,4,5"
Use String.Split(",") assign the result in to a string array and use what you want.
Heres a VB version. I'm sure its easy to translate to C# though
Dim str as string = "ishan,training"
str = str.split(",")(1)
return str

Categories

Resources