Add space between colon in a string

semicolon symbol
semicolon sign
colon before a list
period before colon

Expected User Inputs:

Apple : 100

Apple:100

Apple: 100

Apple :100

Apple   :   100

Apple  :100

Apple:  100

Expected Result:

Apple : 100

I need only 1 space between the colon :

Code:

 string input = "Apple:100";

 if (input.Contains(":"))
 {
    string firstPart = input.Split(':').First();

    string lastPart = input.Split(':').Last();

    input = firstPart.Trim() + " : " + lastPart.Trim();
 }

Above code is working using Linq, but is there shorter or efficient code with performance in mind ?

Any help would be appreciated.

You can use this one liner:

input = string.Join(" : ", input.Split(':').Select(x => x.Trim()));

This is more efficient than splitting two times. However, if you want a more efficient solution you can use StringBuilder:

var builder = new StringBuilder(input.Length);
char? previousChar = null;
foreach (var ch in input)
{
    // don't add multiple whitespace
    if (ch == ' ' && previousChar == ch)
    {
        continue;
    }

     // add space before colon
     if (ch == ':' && previousChar != ' ')
     {
         builder.Append(' ');
     }

     // add space after colon
     if (previousChar == ':' && ch != ' ')
     {
          builder.Append(' ');
     }


    builder.Append(ch);
    previousChar = ch;
}

Edit: As mentioned in the comments by @Jimi seems like the foreach version is slower than LINQ.

Access 2003 Bible, Concatenation operators can combine two strings, a string and an expression, of space between the colon and the 8 is not an error; if you want to add a space  1) How to insert space between every 3 numbers in the string? please help me to insert space between every 3 numbers in the string using concatenate command. eg: string: 100838490382 expected output : 100 838 490 382. Solution. v_temp1 = str+0(3). v_temp2 = str+3(3). v_temp3 = str+6(3). v_temp4 = str+9(3).

You can try this old-fashioned string manipulation:

int colonPos = input.IndexOf(':');
if (colonPos>-1)
{
    string s1 = input.Substring(0,colonPos).Trim();
    string s2 = input.Substring(colonPos+1, input.Length-colonPos-1).Trim();
    string result = $"{s1} : {s2}";
}

Whether it is more performant, I don't know, Race Your Horses.

Edit: This one is even faster and simpler (completed 100000 iterations of the training set in 0.132 seconds):

string result = input.Replace(" ","").Replace(":", " : ");

C# - Spaces, remove_all : Remove all extra spaces. leave_tabs : Leave Before Parentheses in Statements class C { public abstract void Method1 (string str); public abstract void Method2(); }. Copied! Before type parameter constraint colon. Property  In Excel, you can also use the Find and Replace function to replace the comma by comma + space, you can do as following steps: 1. Select the data range that you want to add spaces after commas. 2. Then click Home > Find & Select > Replace or you can press Ctrl + H keys to open the Find and Replace dialog box.

Since you asked, here's a comparison between similar methods:

The two methods that Selman Genç presented and two other that differ in some details.

string.Join("[Separator]", string.Split())

This method glues together, using a Separator, the array of strings generated by .Split(char[]), which creates a string for each substring of the original one. The substrings are generated using the characters specified in the char array parameter as separator identifiers. The StringSplitOptions.RemoveEmptyEntries parameter indicates to only return non-empty substrings.

string output = string.Join(" : ", input.Split(new[] { ":", " " }, StringSplitOptions.RemoveEmptyEntries));

StringBuilder.Append(SubString(IndexOf([Separator]))) (non optimized: TrimStart() and TrimEnd() are used here)

StringBuilder sb = new StringBuilder();
const string Separator = " : ";
int SplitPosition = input.IndexOf(':');
sb.Append(input.Substring(0, SplitPosition).TrimEnd());
sb.Append(Separator);
sb.Append(input.Substring(SplitPosition + 1).TrimStart());

Here are the result of the test in 5 different conditions: (Where I remind myself to always test the .exe and not the IDE)

Debug Mode 32Bit - Visual Studio IDE Debug Mode 64Bit - Visual Studio IDE Release Mode 64Bit - Visual Studio IDE Debug Mode 64Bit - Executable File Release Mode 64Bit - Executable File

Test Machine: I5 4690K on Asus Z-97K MB
Visual Studio 15.8.2
C# 7.3

==========================================
     1 Million iterations x 10 times           
          Code Optimization: On
==========================================
-------------------------------------------
                Debug 32Bit                
-------------------------------------------

Selman Genç Join(.Split().Select()): 244 ~ 247 ms
Selman Genç StringBuilder:           299 ~ 303 ms 
Counter Test Join(.Split()):         187 ~ 226 ms
Counter Test StringBuilder:           90 ~  95 ms

-------------------------------------------
                Debug 64Bit                
-------------------------------------------

Selman Genç Join(.Split().Select()): 242 ~ 259 ms
Selman Genç StringBuilder:           292 ~ 302 ms 
Counter Test Join(.Split()):         183 ~ 227 ms
Counter Test StringBuilder:           89 ~  93 ms

-------------------------------------------
               Release 64Bit                
-------------------------------------------

Selman Genç Join(.Split().Select()): 235 ~ 253 ms
Selman Genç StringBuilder:           288 ~ 302 ms 
Counter Test Join(.Split()):         176 ~ 224 ms
Counter Test StringBuilder:           86 ~  94 ms

-------------------------------------------
          Debug 64Bit - .exe File               
-------------------------------------------

Selman Genç Join(.Split().Select()): 232 ~ 234 ms
Selman Genç StringBuilder:            45 ~  47 ms 
Counter Test Join(.Split()):         197 ~ 217 ms
Counter Test StringBuilder:           77 ~  78 ms

-------------------------------------------
         Release 64Bit - .exe File               
-------------------------------------------

Selman Genç Join(.Split().Select()): 226 ~ 228 ms
Selman Genç StringBuilder:            45 ~  48 ms 
Counter Test Join(.Split()):         190 ~ 208 ms
Counter Test StringBuilder:           73 ~  77 ms

Sample test:

string input = "Apple   :   100";

Stopwatch sw = new Stopwatch();
sw.Start();

// Counter test StringBuilder    
StringBuilder sb1 = new StringBuilder();
const string Separator = " : ";
for (int i = 0; i < 1000000; i++)
{
    int SplitPosition = input.IndexOf(':');
    sb1.Append(input.Substring(0, SplitPosition).TrimEnd());
    sb1.Append(Separator);
    sb1.Append(input.Substring(SplitPosition + 1).TrimStart());
    sb1.Clear();
}
sw.Stop();
//File write
sw.Reset();
sw.Start();

// Selman Genç StringBuilder    
StringBuilder sb2 = new StringBuilder();
for (int i = 0; i < 1000000; i++)
{
    char? previousChar = null;
    foreach (var ch in input)
    {
        if (ch == ' ' && previousChar == ch) { continue; }
        if (ch == ':' && previousChar != ' ') { sb2.Append(' '); }
        if (previousChar == ':' && ch != ' ') { sb2.Append(' '); }

        sb2.Append(ch);
        previousChar = ch;
    }
    sb2.Clear();
}

sw.Stop();
//File write
sw.Reset();
sw.Start();

for (int i = 0; i < 1000000; i++)
{
    string output = string.Join(" : ", input.Split(':').Select(x => x.Trim()));
}

sw.Stop();

/*(...)
*/

Correcting punctuation spacing in a string, Before I start with the logic there are some points that needs addressing : and remove everything else; Apostrophe/single quote ' – remove all spaces; Colon : – remove all spaces The last case [','] , we need to add a space after the comma. There is a trick to strcat. Notice from the documentation, "For character array inputs, strcat removes trailing ASCII white-space characters: space, tab, vertical tab, newline, carriage return, and form feed. For cell and string array inputs, strcat does not remove trailing white space.".

You indicated that the first word would not have any spaces. So in my opinion the most efficient, non-regex solution would be to remove all whitespace from the string (since you dont want any), then just replace the : with :

string input = "Apple   :     100";
input = new string(input.ToCharArray()
                 .Where(c => !Char.IsWhiteSpace(c))
                 .ToArray());
input = input.Replace(":", " : ");

Fiddle here

Automatically adding space before punctuation in LuaLaTeX, If you are implementing French style spacing before double punctuation, you should be aware that the colon obeys different rules: it should be preceded and followed by \begin{luacode} function dosub(s) s = string.gsub(s, '! Something on the lines of public static string splitAndMergeAgain(string original, char splittingChar, bool includeSpaceAfterSplittingChar). Once you split the original string by the splitting char you just trim its components (remove the starting and ending spaces).

You could use Regex:

string input = "Apple:            100";

// Matches zero or more whitespace characters (\s*) followed by 
// a colon and zero or more whitespace characters
string result = Regex.Replace(input, @"\s*:\s*", " : "); // Result: "Apple : 100"

Colon (punctuation), The colon ( : ) is a punctuation mark consisting of two equally sized dots centered on the same vertical line. A colon often precedes an explanation or a list. A colon is also used between hours and minutes, titles and subtitles of books, In modern English-language printing, no space is placed before a colon and a single  Add space between characters and numbers in Microsoft Excel 2013 In this article we will learn how to add space between character and numbers in Microsoft Excel 2010. To understand how to add space between characters and numbers in Excel, we use the below mentioned Data, which is in alpha numeric format.

Using Google App Engine: Building Web Applications, You can also pull out a portion of the string by adding a colon and ending think happythoughts >>> If you wanted to add a space between the words, just add  I am using MS Word 2000. The language is set to English. When I type a colon or semi colon or question mark after a word, an automatic space is placed between the last letter and the symbol.

Formatting, A raw-string literal may have content that exceeds 80 characters. Do not add spaces after the open paren or before the close paren: each case must 4 space indent { break; // 4 space indent } case 1: // no space before the colon { break​  How to split string by line break in Excel. To split text by space, use formulas similar to the ones demonstrated in the previous example. The only difference is that you will need the CHAR function to supply the line break character since you cannot type it directly in the formula.

Sentence Spacing in HTML and CSS, The lazy choice is to add no extra space. You'll get spacing between sentences the same size as spaces between words. This is true no matter how many 

Comments
  • Performance in mind? Is this slow? How often is this executed?
  • @trailmax , it is executed many times.
  • If I understand what you want right and if it's surely will be " 1 word followed by comma followed by number" format always, remove all spaces and then replace ":" with " : " ? Not sure about performance of this approach though.
  • Splitting the input once and storing it in a variable would make your code faster. There's no point splitting it twice.
  • @stom I have provided two solutions, the second one may not work if space comes before apple, I leave fixing that to you :)
  • I find the name lastChar a little disturbing, since last can also mean ultimate. Wouldn't prevChar be more appropriate?
  • @PalleDue yes, it makes more sense. thanks for the suggestion
  • One liner is good one :), this post said Linq has performance issue, what you suggest ?
  • @stom LINQ is not inherently less performant. I'm not sure where you got your info, but it isn't accurate. LINQ does tend to be misused, which can lead to less performant code, I suppose.
  • @stom I saw your previous comment (I was working). If you think it could useful, I can post a couple of examples that perform better (note, a few milliseconds over 1 million operations) than a Linq .Select() method. As I have already mentioned, a StringBuilder.Append() performs even better than string.Join().Split(). You can test them yourself. I can post (as soon as I have some time) an example that uses a StopWatch() to measure the timings, since you already have a bunch of answers here.
  • Appreciate The Work , Thank you :)
  • @stom Take a close look at the timings. What I previously said is not accurate. When run from the executable, the StringBuilder method @Selman Genç provided is the most performat. That's completly different in the VS Environment, where it's the opposite. Since that method doesn't use any "external" helper (like a version of Trim()), it's the most predictable at run-time. The sum of it is, when string concatenation is performed, StringBuilder is the best tool available.
  • At least somebody took a scientific approach and measured the outcome. Have an upvote!
  • Spaces can be after or before Apple but not in the word apple itself.