I want to something as simple as turning "this is a test"
into
new string[] {"t","h","i","s"," ","i","s"," ","a"," ","t","e","s","t"}
Would I really have to do something like
test = "this is a test".Select(x => x.ToString()).ToArray();
edit: To clarify, I don't want a char array, ideally I want an array of string. I don't really see anything wrong with the above code except for the fact that I would think there is an easier way.
Try this:
var charArray = "this is a test".ToCharArray().Select(c=>c.ToString());
string input = "this is a test";
string[] afterSplit = input.Split();
foreach (var word in afterSplit)
Console.WriteLine(word);
Result:
this
is
a
test
Most likely you're looking for the ToCharArray() method. However, you will need to do slightly more work if a string[]
is required, as you noted in your post.
string str = "this is a test.";
char[] charArray = str.ToCharArray();
string[] strArray = str.Select(x => x.ToString()).ToArray();
Edit: If you're worried about the conciseness of the conversion, I suggest you make it into an extension method.
public static class StringExtensions
{
public static string[] ToStringArray(this string s)
{
if (string.IsNullOrEmpty(s))
return null;
return s.Select(x => x.ToString()).ToArray();
}
}
Simple!!
one line:
var res = test.Select(x => new string(x, 1)).ToArray();
Convert the message to a character array, then use a for loop to change it to a string
string message = "This Is A Test";
string[] result = new string[message.Length];
char[] temp = new char[message.Length];
temp = message.ToCharArray();
for (int i = 0; i < message.Length - 1; i++)
{
result[i] = Convert.ToString(temp[i]);
}
You can just use String.ToCharArray() and then treat each char as a string in your code.
Here's an example:
foreach (char c in s.ToCharArray())
Debug.Log("one character ... " +c);
Strings in C# already have a char indexer
string test = "this is a test";
Console.WriteLine(test[0]);
And...
if(test[0] == 't')
Console.WriteLine("The first letter is 't'");
This works too...
Console.WriteLine("this is a test"[0]);
And this...
foreach (char c in "this is a test")
Console.WriteLine(c);
EDIT:
I noticed the question was updated with regards to char[] arrays. If you must have a string[] array, here's how you split a string at each character in c#:
string[] test = Regex.Split("this is a test", string.Empty);
foreach (string s in test)
{
Console.WriteLine(s);
}
Source: Stackoverflow.com