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?
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?
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, ",");
}
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, ",");
String.Insert is the answer:
string test1 = "Hello";
string test2 = test1.Insert(4, ",");
http://msdn.microsoft.com/en-us/library/system.string.insert.aspx
var str ="Hello";
var finalString = string.Format("{0},{1}",str.Substring(0,4),str.Substring(4));
Use below code
String str = "Hello";
str = str.Substring(0, 4) + "," + str.Substring(4, str.Length - 4);
Firstly, strings are immutable so you have to create a new string
var sampleString = "Testing";
var resultString = sampleString.Insert(3, ",);
resultString is "Test,ing"
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