473,386 Members | 1,766 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 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 5044
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 which cpu shoud do every thread? Sincerely Yours,...
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 2003 Regards Frank
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 am using: ...
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 The other multi-list box displays courses based on...
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 the exported functions so I want to replace all my...
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 write a paper about the theory too. Does anyone...
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 would open another report. Anyone know how to modify...
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 and 2 bits are enough to encode them. I want to...
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 re.sub('/\*(.*)/\*' , '/n' , file) but it doesn't work for...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.