-3

I know nothing of C# so I'm hoping somebody here can help. So my question is how would I add a "," after the fourth character in a string. Something like:

Hell,o?

Jeff LaFay
  • 12,882
  • 13
  • 71
  • 101
Adilicious
  • 1,643
  • 4
  • 18
  • 22

8 Answers8

4

You can use .Insert():

string test = "Hello";
test = test.Insert(4, ",");

You should check if the string is long enough though like so:

if (test.Length > 4) {
     test = test.Insert(4, ",");
}
Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
2

You need to use String.Insert and give the number 4 as parameter (since the first char is on place 0)

string s = "hello";
s = s.Insert(4, ",");
Dor Cohen
  • 16,769
  • 23
  • 93
  • 161
  • He doesn't necessarilly **need** to use Insert, also the correct parameter value is 4, since he wants to insert **after** 4th character – Michal Klouda Sep 20 '12 at 12:49
1

Use String.Insert.

E.g. myString.Insert(4, ",");

verdesmarald
  • 11,646
  • 2
  • 44
  • 60
0

String.Insert is the answer:

string test1 = "Hello";
string test2 = test1.Insert(4, ",");

http://msdn.microsoft.com/en-us/library/system.string.insert.aspx

Michal Klouda
  • 14,263
  • 7
  • 53
  • 77
0

var str ="Hello";

var finalString = string.Format("{0},{1}",str.Substring(0,4),str.Substring(4));

Hrishi
  • 350
  • 3
  • 12
0

Use below code

        String str = "Hello";
        str = str.Substring(0, 4) + "," + str.Substring(4, str.Length - 4);
Lajja Thaker
  • 2,031
  • 8
  • 33
  • 53
0

Firstly, strings are immutable so you have to create a new string

var sampleString = "Testing";

var resultString = sampleString.Insert(3, ",);

resultString is "Test,ing"

bstack
  • 2,466
  • 3
  • 25
  • 38
0

I'm gonna Propose an alternative to insert, this way it'll be possible for future users to use for editing a longer string and put in values at different intervals eg.

"hello my name is Anders" becomes "hell,o my, nam,e is, And,ers"

A string in C# is basically an array of chars, so you could loop through it and when you reach the fourth loop you could insert your ,

something like this

string hello="hello";
string newvar ="";
foreach(int i =0;i<hello.length;i++)
{
    if(i==4)
    newvar+=",";
    newvar+=hello[i];
}

if you want it to be each fourth space you can check if 0%=4/i

you can also use Substring split it up into multiple pieces put in your "," and put it back together, I suggest you take a look at the documentation for the string class at Microsofts homepage

Anders M.
  • 199
  • 2
  • 14