• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 479
  • Last Modified:

Inserting a space into String

HI All,

Lets say I have the following random string - ox228rg,

Could anyone show me a C# example of inserting a space before the 3rd character on the right so that the string looks like so - ox22 8rg

Many thanks,

Rit
0
rito1
Asked:
rito1
3 Solutions
 
anarki_jimbelCommented:
Try:
string s = "ox228rg";
            string s2 = s.Substring(0, s.Length - 3) + " " + s.Substring(s.Length - 3, 3);

            MessageBox.Show(s2);

Open in new window

0
 
Jini JoseSenior .Net DeveloperCommented:

string a = "ox228rg";
            char sp = Convert.ToChar(" ");
            a.Insert(4, " ");
            Console.Write(a);

Open in new window

0
 
anarki_jimbelCommented:
gmailjini, you have made a common mistake. The output will be : "ox228rg"!

Just fix the line:

a = a.Insert(4, " ");
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

 
cyberkiwiCommented:
string s = "ox228rg";
s = s.Length <= 3 ? s : s.Insert(s.Length-3, " "); // handle short strings
0
 
Jini JoseSenior .Net DeveloperCommented:
sorry.
you can use the below one

string a = "ox228rg";
            char sp = Convert.ToChar(" ");
            string b=a.Insert(4, sp.ToString());

            Console.Write(b);
0
 
anarki_jimbelCommented:
If go with  code, I'd still modify it to insert not in to the 4th index, but before the 3d from the end character:

Great respect to NZ kiwis! :) Very good idea to check for short strings!
            string a = "ox228rg";
            char sp = Convert.ToChar(" ");
            a = a.Insert(a.Length-3, " ");

            MessageBox.Show(a);

Open in new window

0
 
rito1Author Commented:
Hi All,

Thanks for you input. Apologies for the delay.. sickness struck!... I am picking this back up today so will respond shortly.

Regard,

Rit
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now