Split a string into an array c# [duplicate] - c#

This question already has answers here:
Convert comma separated string of ints to int array
(9 answers)
Closed 8 years ago.
I have a string in C#. It's blank at the beginning, but eventually it will become something like
public string info12 = "0, 50, 120, 10";
One of you might be thinking, eh? Isn't than an integer array? Well it needs to stay a string for the time being, it must be a string.
How can I convert this string into an string array (Variable info13) so I can eventually reference it into more variables.
info 14 = info13[0];
info 15 = info13[1];
PLEASE NOTE: This is not a duplicate question. If you read the whole thing, I clearly stated that I have an array of strings not integers.

Here are a few options:
1. String.Split with char and String.Trim
Use string.Split and then trim the results to remove extra spaces.
public string[] info13 = info12.Split(',').Select(str => str.Trim()).ToArray();
Remember that Select needs using System.Linq;
2. String.Split with char array
No need for trim, although this method is not my favorite
public string[] info13 = info12.Split(new string[] { ", " }, StringSplitOptions.None);
3. Regex
public string[] info13 = Regex.Split(info12, ", ");
Which requires using System.Text.RegularExpressions;
EDIT: Because you no longer need to worry about spaces, you can simply do:
public string[] info13 = info12.Split(',');
Which will return a string array of the split items.

Related

how to use Any(char.IsDigit) to extract the int value [duplicate]

This question already has answers here:
How can I parse the int from a String in C#?
(4 answers)
Closed 3 months ago.
I have this line of code
bool containsInt = "Sanjay 400".Any(char.IsDigit)
What I am trying to do is extract the 400 from the string but
Any(char.IsDigit)
only returns a true value. I am very new to coding and c# especially.
As you already found out, you cannot use Any for extraction.
You would need to use the Where method:
List<char> allInts = "Sanjay 400".Where(char.IsDigit).ToList();
The result will be a list containing all integers/digits from your string.
Ok if you are interested in the value as integer you would need to convert it again to a string and then into an integer. Fortunately string has a nice constructor for this.
char[] allIntCharsArray = "Sanjay 400".Where(char.IsDigit).ToArray();
int theValue = Convert.ToInt32(new string(allIntCharsArray));
If you are using .NET 5 or higher you could also use the new cool TryParse method without extra string conversion:
int.TryParse(allIntCharsArray, out int theValue);
int result = int.Parse(string.Concat("Sanjay 400".Where(char.IsDigit)));
Use the Regex
var containsInt = Convert.ToInt32(Regex.Replace(#"Sanjay 400", #"\D", ""));
Regular expressions allow you to take only numbers and convert them into integers.

Remove strings till a char is recognized [duplicate]

This question already has answers here:
How to remove a defined part of a string?
(8 answers)
Closed 1 year ago.
I am trying to delete parts of the string (first 10 chars) so that I get the serial code of the string without any extra chars. Now, the serial code will always begin after the ":" colon char. So is there a way to specify to delete strings from ":" and before that so that only remaining string would be the serial key?
for example;
string is "MySerials:12e42-23w6z-23w-a23"
final string must be "12e42-23w6z-23w-a23"
I am deleting the strings manually;
public string myStr;
public void Start () {
myStr = myStr.Substring (10, myStr.Length - 10);
Debug.Log (myStr);
}
I would use the string split function like so:
var teststring = "MySerials:12e42-23w6z-23w-a23";
var split = teststring.Split(':');
Console.WriteLine(split[1]);
Instead of splitting the string you could look for the first occurrence of ':' and get your result directly:
var input = "MySerials:12e42-23w6z-23w-a23";
var result = input.Substring(input.IndexOf(':') + 1);

Make all elements of a string[] array into a single string with linq [duplicate]

This question already has answers here:
convert string array to string
(9 answers)
Closed 3 years ago.
say I have an array with some strings in it
string[] array = {"item1", "item2"};
and now I want to use linq to on a single line take all the strings and put them into an array with a space between them
I have tried
args.Select(x => x.ToString() + " ").ToString()
but this returns
It is important to me that the code is on a single line of code, as it is not very clean in my standards or fitting to loop through with a foreach and add it to a string
Try String.Join(" ", array); it should do the trick

Convert a String to a String[], splitted by characters in C# [duplicate]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
The community reviewed whether to reopen this question 7 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
How to convert string type to string[] type in C#?
string[] is an array (vector) of strings
string is just a string (a list/array of characters)
Depending on how you want to convert this, the canonical answer could be:
string[] -> string
return String.Join(" ", myStringArray);
string -> string[]
return new []{ myString };
An array is a fixed collection of same-type data that are stored contiguously and that are accessible by an index (zero based).
A string is a sequence of characters.
Hence a String[] is a collection of Strings.
For example:
String foo = "Foo"; // one instance of String
String[] foos = new String[] { "Foo1", "Foo2", "Foo3" };
String firstFoo = foos[0]; // "Foo1"
Arrays (C# Programming Guide)
Edit: So obviously there's no direct way to convert a single String to an String[]
or vice-versa. Though you can use String.Split to get a String[] from a String by using a separator(for example comma).
To "convert" a String[] to a String(the opposite) you can use String.Join. You need to specify how you want to join those strings(f.e. with comma).
Here's an example:
var foos = "Foo1,Foo2,Foo3";
var fooArray = foos.Split(','); // now you have an array of 3 strings
foos = String.Join(",", fooArray); // now you have the same as in the first line
If you want to convert a string like "Mohammad" to String[] that contains all characters as String, this may help you:
"Mohammad".ToCharArray().Select(c => c.ToString()).ToArray()
You can create a string[] (string array) that contains your string like :
string someString = "something";
string[] stringArray = new string[]{ someString };
The variable stringArray will now have a length of 1 and contain someString.
To convert a string with comma separated values to a string array use Split:
string strOne = "One,Two,Three,Four";
string[] strArrayOne = new string[] {""};
//somewhere in your code
strArrayOne = strOne.Split(',');
Result will be a string array with four strings:
{"One","Two","Three","Four"}
zerkms told you the difference. If you like you can "convert" a string to an array of strings with length of 1.
If you want to send the string as a argument for example you can do like this:
var myString = "Test";
MethodThatRequiresStringArrayAsParameter( new[]{myString} );
I honestly can't see any other reason of doing the conversion than to satisty a method argument, but if it's another reason you will have to provide some information as to what you are trying to accomplish since there is probably a better solution.
string is a string, and string[] is an array of strings
A string is one string, a string[] is a string array. It means it's a variable with multiple strings in it.
Although you can convert a string to a string[] (create a string array with one element in it), it's probably a sign that you're trying to do something which you shouldn't do.
Casting can also help converting string to string[]. In this case, casting the string with ToArray() is demonstrated:
String myString = "My String";
String[] myString.Cast<char>().Cast<string>().ToArray();
A string holds one value, but a string[] holds many strings, as it's an array of string.
See more here
In case you are just a beginner and want to split a string into an array of letters but didn't know the right terminology for that is a char[];
String myString = "My String";
char[] characters = myString.ToCharArray();
If this is not what you were looking for, sorry for wasting your time :P

How to convert string to string[]? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
The community reviewed whether to reopen this question 7 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
How to convert string type to string[] type in C#?
string[] is an array (vector) of strings
string is just a string (a list/array of characters)
Depending on how you want to convert this, the canonical answer could be:
string[] -> string
return String.Join(" ", myStringArray);
string -> string[]
return new []{ myString };
An array is a fixed collection of same-type data that are stored contiguously and that are accessible by an index (zero based).
A string is a sequence of characters.
Hence a String[] is a collection of Strings.
For example:
String foo = "Foo"; // one instance of String
String[] foos = new String[] { "Foo1", "Foo2", "Foo3" };
String firstFoo = foos[0]; // "Foo1"
Arrays (C# Programming Guide)
Edit: So obviously there's no direct way to convert a single String to an String[]
or vice-versa. Though you can use String.Split to get a String[] from a String by using a separator(for example comma).
To "convert" a String[] to a String(the opposite) you can use String.Join. You need to specify how you want to join those strings(f.e. with comma).
Here's an example:
var foos = "Foo1,Foo2,Foo3";
var fooArray = foos.Split(','); // now you have an array of 3 strings
foos = String.Join(",", fooArray); // now you have the same as in the first line
If you want to convert a string like "Mohammad" to String[] that contains all characters as String, this may help you:
"Mohammad".ToCharArray().Select(c => c.ToString()).ToArray()
You can create a string[] (string array) that contains your string like :
string someString = "something";
string[] stringArray = new string[]{ someString };
The variable stringArray will now have a length of 1 and contain someString.
To convert a string with comma separated values to a string array use Split:
string strOne = "One,Two,Three,Four";
string[] strArrayOne = new string[] {""};
//somewhere in your code
strArrayOne = strOne.Split(',');
Result will be a string array with four strings:
{"One","Two","Three","Four"}
zerkms told you the difference. If you like you can "convert" a string to an array of strings with length of 1.
If you want to send the string as a argument for example you can do like this:
var myString = "Test";
MethodThatRequiresStringArrayAsParameter( new[]{myString} );
I honestly can't see any other reason of doing the conversion than to satisty a method argument, but if it's another reason you will have to provide some information as to what you are trying to accomplish since there is probably a better solution.
string is a string, and string[] is an array of strings
A string is one string, a string[] is a string array. It means it's a variable with multiple strings in it.
Although you can convert a string to a string[] (create a string array with one element in it), it's probably a sign that you're trying to do something which you shouldn't do.
Casting can also help converting string to string[]. In this case, casting the string with ToArray() is demonstrated:
String myString = "My String";
String[] myString.Cast<char>().Cast<string>().ToArray();
A string holds one value, but a string[] holds many strings, as it's an array of string.
See more here
In case you are just a beginner and want to split a string into an array of letters but didn't know the right terminology for that is a char[];
String myString = "My String";
char[] characters = myString.ToCharArray();
If this is not what you were looking for, sorry for wasting your time :P

Categories