473,409 Members | 2,022 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,409 software developers and data experts.

Converting Char[] to String?

I need to force the first letter of each word in a line of text to
uppercase. The text comes from a TextBox control in a Web Form. I'm new to
..NET and am having a problem.

Since I can't modify the string directly, I convert the string to a char[]
using .ToCharArray() and set the first letter of each word to uppercase. The
problem then is I can't figure out how to convert the char array back to a
string. Whether I use .ToString() from the char[] variable, or
Convert.ToString(), or CharConverter.ConvertToStriong(), I get the same
result - they return a string for the type, i.e."System.Char[]".

How can I convert the contents of the char array back to a string type? Or,
is there a better way for me to force capitalization of the first letter of
each word in a string?

Thanks
Nov 16 '05 #1
18 7895

"Marcio Kleemann" <notavailable> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
I need to force the first letter of each word in a line of text to
uppercase. The text comes from a TextBox control in a Web Form. I'm new to
.NET and am having a problem.

Since I can't modify the string directly, I convert the string to a char[]
using .ToCharArray() and set the first letter of each word to uppercase. The problem then is I can't figure out how to convert the char array back to a
string. Whether I use .ToString() from the char[] variable, or
Convert.ToString(), or CharConverter.ConvertToStriong(), I get the same
result - they return a string for the type, i.e."System.Char[]".

How can I convert the contents of the char array back to a string type? Or, is there a better way for me to force capitalization of the first letter of each word in a string?


char[] chars . . .
string s = new string(chars);

And there's no better, or at least no faster way than string>char[]>string.

David
Nov 16 '05 #2
Marcio,
Here is an example of what I think you might be trying to do:

<snip>
using System;

class StringTest
{
public static void Main()
{
String s = "this is a Test";

Console.WriteLine( CapFirstWord( s ) );
}

public static String CapFirstWord( String Line )
{
String ReturnString = String.Empty;

for( int i=0; i<Line.Length; i++ )
{
if ( i == 0 )
ReturnString = Char.ToUpper( Line[i] ).ToString();
else
ReturnString += Char.ToLower( Line[i] ).ToString();
}

return ReturnString;
}
}
</snip>

Patrick Altman

"Marcio Kleemann" <notavailable> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
I need to force the first letter of each word in a line of text to
uppercase. The text comes from a TextBox control in a Web Form. I'm new to
.NET and am having a problem.

Since I can't modify the string directly, I convert the string to a char[]
using .ToCharArray() and set the first letter of each word to uppercase. The problem then is I can't figure out how to convert the char array back to a
string. Whether I use .ToString() from the char[] variable, or
Convert.ToString(), or CharConverter.ConvertToStriong(), I get the same
result - they return a string for the type, i.e."System.Char[]".

How can I convert the contents of the char array back to a string type? Or, is there a better way for me to force capitalization of the first letter of each word in a string?

Thanks

Nov 16 '05 #3
<"David Browne" <davidbaxterbrowne no potted me**@hotmail.com>> wrote:
How can I convert the contents of the char array back to a string type?
Or, is there a better way for me to force capitalization of the first letter
of each word in a string?


char[] chars . . .
string s = new string(chars);

And there's no better, or at least no faster way than string>char[]>string.


Nope - using StringBuilder is faster unless the strings are
particularly short, because it means only one extra copy is needed. If
the strings are all very short, then constructing the StringBuilder
makes it a bit slower than using the array version.

Below is a benchmark. Here are the results on my laptop:

string->char[]->string: 00:00:52.2968750
string->StringBuilder->string: 00:00:44.2968750

using System;
using System.Text;

class Test
{
const int Iterations = 50000;

static readonly string[] TestStrings =
{
"a pretty short string",
new string('x', 10000),
new string('y', 100000)
};

static void Main()
{
{
DateTime start = DateTime.Now;
for (int i=0; i < Iterations; i++)
{
foreach (string x in TestStrings)
{
UpperCase1(x);
}
}
DateTime end = DateTime.Now;
Console.WriteLine ("string->char[]->string: {0}",
end-start);
}
{
DateTime start = DateTime.Now;
for (int i=0; i < Iterations; i++)
{
foreach (string x in TestStrings)
{
UpperCase2(x);
}
}
DateTime end = DateTime.Now;
Console.WriteLine ("string->StringBuilder->string: {0}",
end-start);
}
}

static string UpperCase1 (string original)
{
char[] chars = original.ToCharArray();
chars[0]=Char.ToUpper(chars[0]);
return new string(chars);
}

static string UpperCase2 (string original)
{
StringBuilder builder = new StringBuilder(original);
builder[0] = Char.ToUpper(original[0]);
return builder.ToString();
}
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #4
<"Patrick Altman" <paltmanATgmailDOTcom>> wrote:
Marcio,
Here is an example of what I think you might be trying to do:

<snip>
using System;

class StringTest
{
public static void Main()
{
String s = "this is a Test";

Console.WriteLine( CapFirstWord( s ) );
}

public static String CapFirstWord( String Line )
{
String ReturnString = String.Empty;

for( int i=0; i<Line.Length; i++ )
{
if ( i == 0 )
ReturnString = Char.ToUpper( Line[i] ).ToString();
else
ReturnString += Char.ToLower( Line[i] ).ToString();
}

return ReturnString;
}
}


That's a terrible way to do it, unfortunately - using string
concatenation will make this incredibly slow and give a lot of memory
churn when the size of the string increases. Fortunately, it's
unnecessary - see other posts - but in general when building a string
in this kind of way, StringBuilder is the way to go.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #5
Jon,

You are correct. After borrowing some of code in a previous message on this
thread, it's easy to see that StringBuilder is a little more than twice as
fast as concatenation. Thanks for that catch -- learned something new
today!

Patrick Altman

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
<"Patrick Altman" <paltmanATgmailDOTcom>> wrote:
Marcio,
Here is an example of what I think you might be trying to do:

<snip>
using System;

class StringTest
{
public static void Main()
{
String s = "this is a Test";

Console.WriteLine( CapFirstWord( s ) );
}

public static String CapFirstWord( String Line )
{
String ReturnString = String.Empty;

for( int i=0; i<Line.Length; i++ )
{
if ( i == 0 )
ReturnString = Char.ToUpper( Line[i] ).ToString();
else
ReturnString += Char.ToLower( Line[i] ).ToString();
}

return ReturnString;
}
}


That's a terrible way to do it, unfortunately - using string
concatenation will make this incredibly slow and give a lot of memory
churn when the size of the string increases. Fortunately, it's
unnecessary - see other posts - but in general when building a string
in this kind of way, StringBuilder is the way to go.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #6
"Marcio Kleemann" <notavailable> wrote:
How can I convert the contents of the char array
back to a string type?
char[] c = new char[] { 'a', 'b', 'c' };
string s = new string(c);
Or, is there a better way for me to force
capitalization of the first letter of each word
in a string?


Well, I don't see why you can't just iterate over the string and
either make a copy or modify a StringBuilder. I don't think I'd bother
converting it to a char array, personally.

P.
Nov 16 '05 #7
"David Browne" <davidbaxterbrowne no potted me**@hotmail.com> wrote:
is there a better way for me to force capitalization
of the first letter of each word in a string?


[...] there's no better, or at least no faster way than
string>char[]>string.


I'm thinking that String.Split might be handy to break up the words
efficiently; then you'd only have to capitalise each resulting word
instead of scanning through all the characters. It may not be any
faster (depending on underlying implementation), but it's perhaps
simpler.

P.
Nov 16 '05 #8
<"Patrick Altman" <paltmanATgmailDOTcom>> wrote:
You are correct. After borrowing some of code in a previous message on this
thread, it's easy to see that StringBuilder is a little more than twice as
fast as concatenation. Thanks for that catch -- learned something new
today!


The "little more than twice" depends on the length of the original
string. For very short strings, your way may actually be faster. For
very long strings, however, it could be much, *much* slower - millions
of times slower! (Basically the StringBuilder solution is O(n) whereas
using concatenation is O(n^2).)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #9
So, in applying this knowledge of StringBuilder versus Concatenation, what
should be the general rule of thumb of when to use either one? Is there a
some threshold of string length that it is more efficient to use one over
the other? What lengths qualify for "very long strings"?

Thanks,
Patrick Altman
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
<"Patrick Altman" <paltmanATgmailDOTcom>> wrote:
You are correct. After borrowing some of code in a previous message on this thread, it's easy to see that StringBuilder is a little more than twice as fast as concatenation. Thanks for that catch -- learned something new
today!


The "little more than twice" depends on the length of the original
string. For very short strings, your way may actually be faster. For
very long strings, however, it could be much, *much* slower - millions
of times slower! (Basically the StringBuilder solution is O(n) whereas
using concatenation is O(n^2).)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #10
Rule of thumb... if you would build anything more then 3 characters one
character at a time... you should use StringBuilder. If you don't know how
long they'll be... use StringBuilder.

In case you don't know ... any time you make any change to a string, a whole
new string gets created (new memory allocation.) So the rule is not really
on the length of the string, but on how many operations you will do to it.

-Rachel

"Patrick Altman" <paltmanATgmailDOTcom> wrote in message
news:OB*************@TK2MSFTNGP09.phx.gbl...
So, in applying this knowledge of StringBuilder versus Concatenation, what
should be the general rule of thumb of when to use either one? Is there a
some threshold of string length that it is more efficient to use one over
the other? What lengths qualify for "very long strings"?

Thanks,
Patrick Altman
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
<"Patrick Altman" <paltmanATgmailDOTcom>> wrote:
You are correct. After borrowing some of code in a previous message
on
this thread, it's easy to see that StringBuilder is a little more than
twice
as fast as concatenation. Thanks for that catch -- learned something new
today!


The "little more than twice" depends on the length of the original
string. For very short strings, your way may actually be faster. For
very long strings, however, it could be much, *much* slower - millions
of times slower! (Basically the StringBuilder solution is O(n) whereas
using concatenation is O(n^2).)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too


Nov 16 '05 #11
<"Patrick Altman" <paltmanATgmailDOTcom>> wrote:
So, in applying this knowledge of StringBuilder versus Concatenation, what
should be the general rule of thumb of when to use either one? Is there a
some threshold of string length that it is more efficient to use one over
the other? What lengths qualify for "very long strings"?


Any time you build a string within a loop, I'd suggest using
StringBuilder. If you're building it in code, eg

string x = "hello ";
x += "there ";
x += "my ";
x += "name ";
x += "is ";
x += "Jon.";

then you might apply some kind of "more than 5 or 10 concatenations =>
use a StringBuilder" rule of thumb, but it's unlikely to make a huge
difference. Using it in a loop (especially when you don't know the
number of iterations ahead of time) is the potential performance
killer.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #12

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
<"David Browne" <davidbaxterbrowne no potted me**@hotmail.com>> wrote:
How can I convert the contents of the char array back to a string type? Or, is there a better way for me to force capitalization of the first letter of each word in a string?
char[] chars . . .
string s = new string(chars);

And there's no better, or at least no faster way than

string>char[]>string.
Nope - using StringBuilder is faster unless the strings are
particularly short, because it means only one extra copy is needed.


Ahh, I forgot that StringBuilder.ToString() cheats, not returning a copy
like we mere mortals would have to.

David
Nov 16 '05 #13
On 2004-08-20, Jon Skeet [ C# MVP ] <sk***@pobox.com> wrote:
<"David Browne" <davidbaxterbrowne no potted me**@hotmail.com>> wrote:
> How can I convert the contents of the char array back to a string type?
> Or, is there a better way for me to force capitalization of the first letter
> of each word in a string?


char[] chars . . .
string s = new string(chars);

And there's no better, or at least no faster way than string>char[]>string.


Nope - using StringBuilder is faster unless the strings are
particularly short, because it means only one extra copy is needed. If
the strings are all very short, then constructing the StringBuilder
makes it a bit slower than using the array version.

Of course, the assumption that the strings are very short is a pretty
reasonable assumption in the original post, since we're dealing with a
single line of text of (presumably) english words.

Nov 16 '05 #14
On 2004-08-20, Marcio Kleemann <> wrote:
How can I convert the contents of the char array back to a string type? Or,
is there a better way for me to force capitalization of the first letter of
each word in a string?


Personally, I'd probably go for a regular expression here, just because
I find it much shorter and much easier to read, assuming you're used to
regexes...

public string UpperCaseWords(string input)
{
return Regex.Replace(s, @"\b\w", new MatchEvaluator(UpperCaseMatches));
}

private string UpperCaseMatches(Match match)
{
return match.value.ToUpper();
}
Nov 16 '05 #15
David <df*****@woofix.local.dom> wrote:
And there's no better, or at least no faster way than string>char[]>string.


Nope - using StringBuilder is faster unless the strings are
particularly short, because it means only one extra copy is needed. If
the strings are all very short, then constructing the StringBuilder
makes it a bit slower than using the array version.


Of course, the assumption that the strings are very short is a pretty
reasonable assumption in the original post, since we're dealing with a
single line of text of (presumably) english words.


By "particularly short" here, I mean really, really short - just a very
few characters. Even with just 50 characters you end up shuffling about
2.5K around instead of 100 bytes, if you use repeated concatenation.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #16
On 2004-08-21, Jon Skeet [ C# MVP ] <sk***@pobox.com> wrote:
David <df*****@woofix.local.dom> wrote:
>
> Nope - using StringBuilder is faster unless the strings are
> particularly short, because it means only one extra copy is needed. If
> the strings are all very short, then constructing the StringBuilder
> makes it a bit slower than using the array version.


Of course, the assumption that the strings are very short is a pretty
reasonable assumption in the original post, since we're dealing with a
single line of text of (presumably) english words.


By "particularly short" here, I mean really, really short - just a very
few characters. Even with just 50 characters you end up shuffling about
2.5K around instead of 100 bytes, if you use repeated concatenation.


In some simple benchmarking (obviously not guaranteed accurate), the two
techniques seem to even out at about 20-25 characters, which seems to me
to be the upper end of natural length for the things you'd probably want
to capitalize: titles and proper names (names and popular titles are
generally shorter, but academic titles are often much longer).

Although I might have subthreads confused here, but I thought the
repeated concatenation code was in another subthread. This particular
line of posts was merely comparing the string.ToCharArray() and new
string(char[]) vs. new StringBuilder(string) and builder.ToString().
Neither of those is going to be pushing 2.5K around for a 50 byte
string, AFAIK.
Nov 16 '05 #17
David <df*****@woofix.local.dom> wrote:
> Nope - using StringBuilder is faster unless the strings are
> particularly short, because it means only one extra copy is needed. If
> the strings are all very short, then constructing the StringBuilder
> makes it a bit slower than using the array version.

Of course, the assumption that the strings are very short is a pretty
reasonable assumption in the original post, since we're dealing with a
single line of text of (presumably) english words.
By "particularly short" here, I mean really, really short - just a very
few characters. Even with just 50 characters you end up shuffling about
2.5K around instead of 100 bytes, if you use repeated concatenation.


In some simple benchmarking (obviously not guaranteed accurate), the two
techniques seem to even out at about 20-25 characters, which seems to me
to be the upper end of natural length for the things you'd probably want
to capitalize: titles and proper names (names and popular titles are
generally shorter, but academic titles are often much longer).


Hmm... I saw things evening out between 10 and 15 characters. By 20
characters StringBuilder has the upper hand. It's pretty much of a
muchness in that range though, yes.
Although I might have subthreads confused here, but I thought the
repeated concatenation code was in another subthread. This particular
line of posts was merely comparing the string.ToCharArray() and new
string(char[]) vs. new StringBuilder(string) and builder.ToString().
Neither of those is going to be pushing 2.5K around for a 50 byte
string, AFAIK.


You're absolutely right on this bit - that's what comes of me posting
before I'm properly awake.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #18
Thanks to everyone for the detailed replies and comparisons between the
various possibilities!

"Marcio Kleemann" <notavailable> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
I need to force the first letter of each word in a line of text to
uppercase. The text comes from a TextBox control in a Web Form. I'm new to
.NET and am having a problem.

Since I can't modify the string directly, I convert the string to a char[]
using .ToCharArray() and set the first letter of each word to uppercase. The problem then is I can't figure out how to convert the char array back to a
string. Whether I use .ToString() from the char[] variable, or
Convert.ToString(), or CharConverter.ConvertToStriong(), I get the same
result - they return a string for the type, i.e."System.Char[]".

How can I convert the contents of the char array back to a string type? Or, is there a better way for me to force capitalization of the first letter of each word in a string?

Thanks

Nov 16 '05 #19

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

Similar topics

5
by: matt melton | last post by:
Hi there, I am trying to write a method that accepts an array of any primitive type and will return the same array without copying memory as an array of bytes. ie. I'd like to be able to do...
4
by: Prabhu | last post by:
Hi, We are having problem in converting a byte array to string, The byte array has char(174), char(175), char(240), char(242) and char(247) as delimiters for the message. when we use...
3
by: fakeprogress | last post by:
How would I go about converting this C code to C++? /* LIBRARY is an array of structures */ /* This function compares 'tcode' with */ /* existing codes in the array. */ /* It...
2
by: pookiebearbottom | last post by:
Just looking for opinion on which of the 3 methods below people use in their code when they convert a 'const char *' to a 'const std::string &' came across #3 in someone's code and I had to...
0
by: anide | last post by:
Hi all I’ve some problem, I’m trying to converting a sorting algorithm from C++ to C#. In C++ I’ve compiled it using MSVC and its working properly, and in C# I’m using .NET Framework 2.0 (Visual...
2
by: CoreyWhite | last post by:
Problem: You have numbers in string format, but you need to convert them to a numeric type, such as an int or float. Solution: You can do this with the standard library functions. The...
5
by: Hans Mull | last post by:
Hi! How can I convert a string to a const unsigned char*? (string::c_str() converts the string to a signed char) Thanks in advance, Hans
1
by: vcbytes | last post by:
I am having a problem with the following code: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { String^ texts = textBox1->Text; char *text =...
4
by: screamer81 | last post by:
Hello, I've a SDK functions description for a scanner and I try to convert unmanaged DLL C++ functions to c#. I converted all except one of them. This function is getting a struct parameter. ...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
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
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.