user3913686
user3913686

Reputation:

How can I add a SPACE halfway through a string value?

I'm trying to create a STRING in JSON format. However, one of the fields (from my editing/removing ALL spaces) now leaves a line like "START":"13/08/1410:30:00". However, I want to add a space between the date and time? I have tried using the ToCharArray() method to split the string, but I am at a loss as to how to add a space between the DATE and TIME part of the string?

For Example, i am trying to get: "START":"13/08/14 10:30:00" but instead am getting

"START":"13/08/1410:30:00"

Please note. The length of the string before the space requirement will always be 17 characters long. I am using VS 2010 for NETMF (Fez Panda II)

Upvotes: 2

Views: 342

Answers (4)

Selman Genç
Selman Genç

Reputation: 101701

If the date time format always the same you can use string.Insert method

var output = @"""START"":""13/08/1410:30:00""".Insert(17, " ");

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062905

If the split position is always 17, then simply:

string t = s.Substring(0, 17) + " " + s.Substring(17);

Upvotes: 1

Callum Linington
Callum Linington

Reputation: 14417

Obviously you will have to sort the numbers out, but thats the general idea.

String.Format("{0} {1}", dateString.Substring(0, 17), dateString.Substring(17, dateString.Length - 17);

Or you can use the StringBuilder class:

var finalString = new StringBuilder();
for (var i = 0; i < dateString.Length; i++){
    if (i == 17)
        finalString.Add(" ");
    else
        finalString.Add(dateString.ToCharArray()[i]);
}
return finalString.ToString();

Upvotes: 1

Falanwe
Falanwe

Reputation: 4744

Strings in .Net are immutable: you can never change them. However, you can easily create a new string.

var date_time = dateString + " " + timeString;

Upvotes: -1

Related Questions