472,336 Members | 1,212 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,336 software developers and data experts.

How to replace multi-spaces within a string with single-space

Hello,

I was wondering if there is a method that exists to replace multi-spaces
within a string with single-space.
eg:
"12 3 4 56" --> "12 3 4 56"

I think this could be done by looking at each char within a loop and copying
the char to a stringBuilder instance
if current and previous char are not spaces...
But as always, I would prefer to use an existing method ;-)

Thanks,
José
Nov 13 '05 #1
2 4954
José Joye <jo*******@KILLTHESPAMSbluewin.ch> wrote:
Yes, in my case, efficiency is a topic. However, I agree that my strings are
quite small and the number of multi-spaces should not be to many.

I was wondering if the Regex solution is slower than the other solutions. If
yes, do you know how much slower?


I really don't know. Could you post a sample selection of strings
(including whatever proportion would have no multi-spaces at all)? If
so, I can benchmark a few ways of doing it...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Nov 13 '05 #2
José Joye <jo*******@KILLTHESPAMSbluewin.ch> wrote:
In fact, my strings are OCR-B lines read from Bank/Post Slips.
Each line should contains at most 80 chars. I have removed the Heading and
leading spaces with the Trim()
method.

So this can be some samples:
"0100 000187004>221 74101 02080003 95200208060+ 010184 473>"
"01 00000179008>0 00050175 7500100007054 24008+ 0103 97904>"
"01 0000006630 3>104922 351100079647820 000008+ 010194507>"
"0 00000000000 000111033122108+ 077782103 >"
"5 00002700>"
"0100000241504>113730619000003472360720026+ 010231043>"


Righto.

Running the code at the bottom, here are the results I got:

Benchmarking type MultiSpace
Run #1
RegexReplace 00:00:51.1034832
RegexReplaceWithTest 00:00:45.9443136
CompiledRegexReplaceWithTest 00:00:15.3420608
StringReplace 00:00:06.0687264
StringBuilderSingleChar 00:00:03.6252128
StringBuilderBlock 00:00:02.1831392
Run #2
RegexReplace 00:00:51.0333824
RegexReplaceWithTest 00:00:45.9260384
CompiledRegexReplaceWithTest 00:00:15.0316144
StringReplace 00:00:06.0386832
StringBuilderSingleChar 00:00:03.6652704
StringBuilderBlock 00:00:02.1330672

It looks like the StringBuilderBlock method is the best by a reasonably
significant margin. The code for that on its own would be:

public static void FlattenSpaces (string x)
{
if (x.IndexOf (" ")==-1)
return x;

StringBuilder builder = new StringBuilder(x.Length);

int start=0;
while (true)
{
int nextDoubleSpace = x.IndexOf (" ", start);
if (nextDoubleSpace==-1)
break;
builder.Append (x, start, nextDoubleSpace+1-start);
start = nextDoubleSpace+2;
while (start < x.Length && x[start]==' ')
start++;
}
builder.Append (x, start, x.Length-start);
return builder.ToString();
}
Benchmark code (run with -runtwice on my box):
// See http://www.pobox.com/~skeet/csharp/benchmark.html
// for how to run this code.

using System;
using System.Text;
using System.Text.RegularExpressions;

public class MultiSpace
{
static readonly string[] TestCases =
{
"0100 000187004>221 74101 02080003 95200208060+ "+
" 010184 473>",
"01 00000179008>0 00050175 7500100007054 24008+ "+
"0103 97904>",
"01 0000006630 3>104922 351100079647820 000008+ 010194507>",
"0 00000000000 000111033122108+ 077782103 >",
"5 00002700>",
"0100000241504>113730619000003472360720026+ 010231043>",
};

static long check;
static int iterations = 100000;

public static void Init(string[] args)
{
if (args.Length != 0)
iterations = Int32.Parse(args[0]);
}

public static void Reset()
{
check=0;
}

public static void Check()
{
if (check != 279*iterations)
throw new Exception ("Invalid check total: "+check);
}

[Benchmark]
public static void RegexReplace()
{
long total=0;

for (int i = iterations; i>0; i--)
{
foreach (string s in TestCases)
{
string x=s;
x = Regex.Replace (x, " +", " ");
total+=x.Length;
}
}
check=total;
}

[Benchmark]
public static void RegexReplaceWithTest()
{
long total=0;

for (int i = iterations; i>0; i--)
{
foreach (string s in TestCases)
{
string x=s;
if (x.IndexOf(" ")!=-1)
x = Regex.Replace (x, " +", " ");
total+=x.Length;
}
}
check=total;
}

static Regex compiledRegex = new Regex (" +",
RegexOptions.Compiled);
[Benchmark]
public static void CompiledRegexReplaceWithTest()
{
long total=0;

for (int i = iterations; i>0; i--)
{
foreach (string s in TestCases)
{
string x=s;
if (x.IndexOf(" ")!=-1)
x = compiledRegex.Replace (x, " ");
total+=x.Length;
}
}
check=total;
}

[Benchmark]
public static void StringReplace()
{
long total=0;

for (int i = iterations; i>0; i--)
{
foreach (string s in TestCases)
{
string x=s;
while (x.IndexOf(" ")!=-1)
x=x.Replace(" ", " ");
total+=x.Length;
}
}
check=total;
}

[Benchmark]
public static void StringBuilderSingleChar()
{
long total=0;

for (int i = iterations; i>0; i--)
{
foreach (string s in TestCases)
{
if (s.IndexOf (" ")==-1)
{
total+=s.Length;
continue;
}

StringBuilder builder = new StringBuilder(s.Length);
bool inSpace=false;
foreach (char c in s)
{
if (c==' ')
{
if (!inSpace)
builder.Append(c);
inSpace=true;
}
else
{
builder.Append(c);
inSpace=false;
}
}
total+=builder.ToString().Length;
}
}
check=total;
}

[Benchmark]
public static void StringBuilderBlock()
{
long total=0;

for (int i = iterations; i>0; i--)
{
foreach (string x in TestCases)
{
if (x.IndexOf (" ")==-1)
{
total+=x.Length;
continue;
}

StringBuilder builder = new StringBuilder(x.Length);

int start=0;
while (true)
{
int nextDoubleSpace = x.IndexOf (" ", start);
if (nextDoubleSpace==-1)
break;
builder.Append (x, start, nextDoubleSpace+1-start);
start = nextDoubleSpace+2;
while (start < x.Length && x[start]==' ')
start++;
}
builder.Append (x, start, x.Length-start);
total+=builder.ToString().Length;
}
}
check=total;
}
}
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Nov 13 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

37
by: ajikoe | last post by:
Hello, Is anyone has experiance in running python code to run multi thread parallel in multi processor. Is it possible ? Can python manage...
4
by: Frank Jona | last post by:
Intellisense with C# and a multi-file assembly is not working. With VB.NET it is working. Is there a fix availible? We're using VisualStudio...
12
by: * ProteanThread * | last post by:
but depends upon the clique: ...
1
by: DBLWizard | last post by:
I have a multiframe page that when you click on a button on the page it changes the content in one of the other frames. This function works and I...
6
by: Joe | last post by:
I have 2 multi-list boxes, 1 displays course categories based on a table called CATEGORIES. This table has 2 fields CATEGORY_ID, CATEGORY_NAME ...
1
by: Torben Laursen | last post by:
Hi I have a dll that is beeing called by C++, VBA, Java and C# One of my customers does not like that I have bool in the argument list of some of...
5
by: bobwansink | last post by:
Hi, I'm relatively new to programming and I would like to create a C++ multi user program. It's for a project for school. This means I will have to...
5
by: dkelly925 | last post by:
Is there a way to add an If Statement to the following code so if data in a field equals "x" it will launch one report and if it equals "y" it...
23
by: Umesh | last post by:
This is a basic thing. Say A=0100 0001 in ASCII which deals with 256 characters(you know better than me!) But we deal with only four characters...
3
by: lex __ | last post by:
I'm tryin to use regexp to replace multi-line c-style comments (like /* this /n */ ) with /n (newlines). I tried someting like ...
0
by: concettolabs | last post by:
In today's business world, businesses are increasingly turning to PowerApps to develop custom business applications. PowerApps is a powerful tool...
0
by: teenabhardwaj | last post by:
How would one discover a valid source for learning news, comfort, and help for engineering designs? Covering through piles of books takes a lot of...
0
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
by: CD Tom | last post by:
This only shows up in access runtime. When a user select a report from my report menu when they close the report they get a menu I've called Add-ins...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.