Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello,

In a program I need to manipulate the input string.
Simply I should put a comma ',' between each two letters of the string.

I used the code below but after modifying the string,
the modified string is not shown well. In other words, suppose

input string : 'Hello'
modified string : 'H,e,l,l,o'

but shown : System.String[]


string inp_str, mod_str; // Input string , modified string
            inp_str = textBox1.Text;
            
            int intLng = inp_str.Length;
            char[] chAray = new char[2*intLng];

            for (int i1 = 0; i1 < inp_str.Length; i1++)
            {
                chAray[2 * i1] = inp_str[i1];
                chAray[2 * i1 + 1] = ',';
            }

            mod_str = chAray.ToString();
            MessageBox.Show(mod_str);


Could you please help me?
Thanks a lot
Posted

An easy way to do this is to use
C#
mod_str = new string(chAray);
The new string constructor is a fast method for creating the string out of an array.
 
Share this answer
 
MIDL
string inp_str, mod_str; 
inp_str = textBox1.Text;
mod_str = string.Join(",", inp_str.ToCharArray());
inp_str = textBox1.Text;
 
Share this answer
 
Comments
ahhashemi 28-Jun-11 5:46am    
Dear Kiran Sonawane
Thank you very much for reading my question but the suggestion faced two errors bellow:

1. The best overloaded method match for 'string.Join(string, string[])' has some invalid arguments

2. Argument '2': cannot convert from 'char[]' to 'string[]'

Regards
Alternative 3 is the good one. However consider even this String concatenation using LINQ to create a CSV/PSV string[^]

Take care
 
Share this answer
 
Comments
Mario Majčica 28-Jun-11 7:00am    
Down-voting without a comment? Really constructive...
inp_str = textBox1.Text;
int intLng = inp_str.Length;
char[] chAray = new char[2 * intLng];
for (int i1 = 0; i1 < inp_str.Length; i1++)
{
   chAray[2 * i1] = inp_str[i1];
   chAray[2 * i1 + 1] = ',';
}

foreach (var item in chAray)
{
   mod_str += item;
}
MessageBox.Show(mod_str);


You might need to change the conversion a bit, because your code adds a comma even after the last character and it ends up looking like:
e,x,a,m,p,l,e,

Might I also suggest you use a StringBuilder type for mod_str and append each character to that, instead of concatenating characters to a String.

Take care
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900