473,408 Members | 1,749 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,408 software developers and data experts.

StringBuilder help

I was in an interview question what is the most efficient way to sort
a string for example "010101", the result would then be "000111", and
write the code on how to do this. I wrote the code for the
interviewers and I was told I did ok, but a stringbuilder would have
been better to use. In this storing the string in an array and
calling the sort method is not a solution for this problem. If anyone
can help explain how using a stringbuilder is better in this way
please let me know and please show the code on how to use the
stringbuilder because I cannot figure it out. I have provided sample
code for what I did. Thanks!

public string GetString(string text)
{
string t1 = string.Empty, t2 = string.Empty;

for(int i = 0; i < text.Length; i++)
{
if(text[i].ToString() == "0")
{
t2 += text[i].ToString();
}
else
{
t2 += text[i].ToString();
}
}

return t1+t2;
}
Dec 26 '07 #1
7 2406

<rh******@gmail.comwrote in message
news:5a**********************************@j64g2000 hsj.googlegroups.com...
>I was in an interview question what is the most efficient way to sort
a string for example "010101", the result would then be "000111", and
write the code on how to do this. I wrote the code for the
interviewers and I was told I did ok, but a stringbuilder would have
been better to use. In this storing the string in an array and
calling the sort method is not a solution for this problem. If anyone
can help explain how using a stringbuilder is better in this way
please let me know and please show the code on how to use the
stringbuilder because I cannot figure it out. I have provided sample
code for what I did. Thanks!

public string GetString(string text)
{
string t1 = string.Empty, t2 = string.Empty;

for(int i = 0; i < text.Length; i++)
{
if(text[i].ToString() == "0")
{
t2 += text[i].ToString();
}
else
{
t2 += text[i].ToString();
}
}

return t1+t2;
}
They didn't like your string concatination because it generates an entirely
new string each time (memory intensive). Also, you never assign anything to
"t1", which is probably a problem. :)

public string GetString(string text)
{
StringBuilder t1 = new StringBuilder();
StringBuilder t2 = new StringBuilder();

for(int i = 0; i < text.Length; i++)
{
if(text[i].ToString() == "0")
{
t1.Append(text[i].ToString());
}
else
{
t2.Append(text[i].ToString());
}
}

return t1.ToString()+t2.ToString();
}
Although, I'm pretty sure that this isn't "optimal" either.

Dec 26 '07 #2
<rh******@gmail.comwrote in message
news:5a**********************************@j64g2000 hsj.googlegroups.com...
>I was in an interview question what is the most efficient way to sort
a string for example "010101", the result would then be "000111", and
write the code on how to do this. I wrote the code for the
interviewers and I was told I did ok, but a stringbuilder would have
been better to use. In this storing the string in an array and
calling the sort method is not a solution for this problem. If anyone
can help explain how using a stringbuilder is better in this way
please let me know and please show the code on how to use the
stringbuilder because I cannot figure it out. I have provided sample
code for what I did. Thanks!

public string GetString(string text)
{
string t1 = string.Empty, t2 = string.Empty;

for(int i = 0; i < text.Length; i++)
{
if(text[i].ToString() == "0")
{
t2 += text[i].ToString();
}
else
{
t2 += text[i].ToString();
}
}

return t1+t2;
}
I came up with a solution that uses the built in Array.Sort method.

static string SortString(string sIn)
{
char[] s = sIn.ToCharArray();
System.Array.Sort(s);
System.Text.StringBuilder sBuilder = new
StringBuilder(sIn.Length);
foreach (char c in s) {
sBuilder.Append(c);
}
return sBuilder.ToString();
}

Basically, convert the string to a char array, sort it, then create a
StringBuilder long enough to contain the entire char array without
reallocation and append the characters to it. Allocations in this method
are:

One allocation to create the char array.
One allocation to create the string builder (size is known from the size
of the input string, so no reallocations are required)
One allocation to convert the string builder to a string.

The char in the foreach loop is probably held on the stack so there are no
heap allocations required.

Mike.
Dec 27 '07 #3
On Wed, 26 Dec 2007 21:24:57 -0800, Michael D. Ober
<obermd.@.alum.mit.edu.nospam.wrote:
I came up with a solution that uses the built in Array.Sort method.

static string SortString(string sIn)
{
char[] s = sIn.ToCharArray();
System.Array.Sort(s);
System.Text.StringBuilder sBuilder = new
StringBuilder(sIn.Length);
foreach (char c in s) {
sBuilder.Append(c);
}
return sBuilder.ToString();
}

Basically, convert the string to a char array, sort it, then create a
StringBuilder long enough to contain the entire char array without
reallocation and append the characters to it.
While I think the general approach is fine (but if I read the OP
correctly, not a valid answer for his situation, since he specifically
wrote "...calling the sort method is not a solution for this problem"),
why use the StringBuilder? Why not just "return new string(s);"? Surely
that's at least as efficient as enumerating each character and adding it
to a StringBuilder.

Pete
Dec 27 '07 #4
Hi

<rh******@gmail.comwrote in message
news:5a**********************************@j64g2000 hsj.googlegroups.com...
>I was in an interview question what is the most efficient way to sort
a string for example "010101", the result would then be "000111", and
write the code on how to do this
What if the string contains more than 1 and 0 ?

--
Ignacio Machin
http://www.laceupsolutions.com
Mobile & warehouse Solutions.
Dec 27 '07 #5
<rh******@gmail.comwrote in message
news:5a**********************************@j64g2000 hsj.googlegroups.com...
>I was in an interview question what is the most efficient way to sort
a string for example "010101", the result would then be "000111", and
write the code on how to do this. I wrote the code for the
interviewers and I was told I did ok, but a stringbuilder would have
been better to use. In this storing the string in an array and
calling the sort method is not a solution for this problem. If anyone
can help explain how using a stringbuilder is better in this way
please let me know and please show the code on how to use the
stringbuilder because I cannot figure it out. I have provided sample
code for what I did. Thanks!
I am curious.
You gave a fairly loose description of the problem statement.
Can you remember it more exactly?

Did he specify that is would only contain '0', '1'?
Did his example only have 6 characters ["010101"] , or did you simplify?
Did he really ask for the "Most efficient"?

Basically, I am wondering if your interviewer knew what he was talking
about.

I will tell you right now that using StringBuilder for the sample you
posted is actually less efficient than string concatenation. The
StringBuilder will become more far efficient on much longer strings, but
in this example the StringBuilder is slower.

Anyway, just curious.
Bill
Dec 27 '07 #6
Hmmm...can the string only contain ones and zeroes???
Your implementation only works for that case.

If so, this is much more simple and faster:

string SortOnesAndZeros(string original)
{
int zeroes = 0;
foreach (char item in original)
{
if (item == '0')
{
zeroes++;
}
}

return new string('0', zeroes) + new string('1', original.Length -
zeroes);
}
If the string can contain any character, maybe this is a better approach:

string SortCharsInString(string original)
{
char[] chars = original.ToCharArray();
Array.Sort(chars);
return new string(chars);
}

Greetings,
<rh******@gmail.comescribió en el mensaje de
noticias:5a**********************************@j64g 2000hsj.googlegroups.com...
I was in an interview question what is the most efficient way to sort
a string for example "010101", the result would then be "000111", and
write the code on how to do this. I wrote the code for the
interviewers and I was told I did ok, but a stringbuilder would have
been better to use. In this storing the string in an array and
calling the sort method is not a solution for this problem. If anyone
can help explain how using a stringbuilder is better in this way
please let me know and please show the code on how to use the
stringbuilder because I cannot figure it out. I have provided sample
code for what I did. Thanks!

public string GetString(string text)
{
string t1 = string.Empty, t2 = string.Empty;

for(int i = 0; i < text.Length; i++)
{
if(text[i].ToString() == "0")
{
t2 += text[i].ToString();
}
else
{
t2 += text[i].ToString();
}
}

return t1+t2;
}

Dec 27 '07 #7
rh******@gmail.com wrote:
I was in an interview question what is the most efficient way to sort
a string for example "010101", the result would then be "000111", and
write the code on how to do this. I wrote the code for the
interviewers and I was told I did ok, but a stringbuilder would have
been better to use. In this storing the string in an array and
calling the sort method is not a solution for this problem. If anyone
can help explain how using a stringbuilder is better in this way
please let me know and please show the code on how to use the
stringbuilder because I cannot figure it out. I have provided sample
code for what I did. Thanks!

public string GetString(string text)
{
string t1 = string.Empty, t2 = string.Empty;

for(int i = 0; i < text.Length; i++)
{
if(text[i].ToString() == "0")
{
t2 += text[i].ToString();
}
else
{
t2 += text[i].ToString();
}
}

return t1+t2;
}
Just out of curiosity, what was the point of this question? Did they
just want to check if you could implement a sorting algorithm? It just
seems random and hypothetical to me... Not the sort of thing I would
want to check in a particular candidate anyway.

--
Lasse Vågsæther Karlsen
mailto:la***@vkarlsen.no
http://presentationmode.blogspot.com/
Dec 28 '07 #8

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

Similar topics

37
by: Kevin C | last post by:
Quick Question: StringBuilder is obviously more efficient dealing with string concatenations than the old '+=' method... however, in dealing with relatively large string concatenations (ie,...
20
by: Alvin Bruney | last post by:
On the advice of a user, I've timed stringbuilder v string. Here are the results. Here are the numbers: Total # queries 3747 Time in Milliseconds StringBuilder: String...
0
by: Mo | last post by:
I am having problem with marshaling struct in C#. //the original C++ struct typedef struct _tagHHP_DECODE_MSG { DWORD dwStructSize; // Size of decode structure. TCHAR ...
3
by: Salvador | last post by:
Hi, I am using an old Win32 DLL that expects a LPBYTE as a parameter. The Stringbuilder appears to be working, the problem is that the component is sending me a string with NULL characters in the...
6
by: Jim Heavey | last post by:
Hello, I a m building an email message in a StringBuilder Object and then using the StringBuilder ToString() method to get it to regular text. It appears to me that when I place a "\n" into the...
8
by: Henning M | last post by:
Hi, I'm trying to use stringbuilder to collect a list of strings. (as suggested by Claes Bergefall) Declare Auto Function CM_Get_Device_ID_List Lib "cfgmgr32.dll" (ByVal pszFilter As String,...
33
by: genc_ymeri | last post by:
Hi over there, Propably this subject is discussed over and over several times. I did google it too but I was a little bit surprised what I read on internet when it comes 'when to use what'. Most...
8
by: Arjan | last post by:
Hello, I have been looking for a couple of days now, but I can't find anything about how to deal with StringBuilder and releasing the memory used by it. When I use stringbuilder, the memory...
5
by: pantagruel | last post by:
Hi, It is generally stated that stringbuilder should be used instead of just concatenating strings with the plus operator. That's fine enough what I'm wondering in cases I have: String S =...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.