Afzaal Ahmad Zeeshan
Afzaal Ahmad Zeeshan

Reputation: 15860

How to split a string at each character

I am using ASP.NET Web Pages to create a project in which I am assigned to place each character of the user's (customer's) name in each seperate input block.

For that I am getting the value from the Sql Server CE Database and then I am trying to convert it into an array of one character for each input. I have tried the following code for that

var form_data = db.QuerySingle("SELECT * FROM Form_Data WHERE Form_Id =@0", form_id);
var name_emp = form_data.Name_Emig;
if(name_emp != null) {
    name_emp = name_emp.ToString().Split('');
}

It generates the following Compiler error:

http://msdn.microsoft.com/en-us/library/8eb78ww7(v=vs.90).aspx (Compiler error: CS1011)

Which means that the character cannot be initialized by an empty value. I want to convert that value in one character each array.

The name is as: Afzaal Ahmad Zeeshan. So, in each input it would be placed inside the value of it. But the code I am using isn't working. Any suggestion to split the string at each character, so the result would be

{'A', 'F', 'Z', 'A', 'A', 'L' ...}

It doesn't matter whether result is Capital case or lower case. I will convert it to the desired one later.

Upvotes: 0

Views: 1266

Answers (3)

TCC
TCC

Reputation: 2596

Try name_emp.ToArray(). A string implements IEnumerable<char>, so ToArray will return an array of the char.

Edit: Actually I suppose ToCharArray is better in this case...

Upvotes: 0

Shmwel
Shmwel

Reputation: 1697

You can try using ToCharArray().

So your code would be this:

var form_data = db.QuerySingle("SELECT * FROM Form_Data WHERE Form_Id =@0", form_id);
var name_emp = form_data.Name_Emig;
if(name_emp != null) {
    name_emp = name_emp.ToCharArray();
}

Upvotes: 3

Only a Curious Mind
Only a Curious Mind

Reputation: 2857

You can use this to iterate with each item :

string yourString = "test";

foreach(var character in yourString)
{
 // do something with each character.
}

Or this to get all characters in a char[]

char[] characters = yourstring.ToCharArray();

Upvotes: 1

Related Questions