473,698 Members | 2,187 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

converting char[] to string

I have a char[] that i convert to a string as follows
m_tHeader.m_ssh ortname is defined as char[8];

string result = new string(m_tHeade r.m_sshortname) ;

The problem is that any '\0' chars in the array remain in the string and
it's not terminated properly.

Is there a nice way to trim these off (string.trim doesnt work) rather than
my very nasty code below

while((result.L ength > 0)&&(result[result.Length - 1] == '\0'))

result = result.Remove(r esult.Length - 1,1);

thanks


Mar 21 '06 #1
2 19399
Hi claire,

Yes, the C# string does not use a null terminator. That is, a C# string may
contain null characters.

Depending on what you want to do with the contents of the string, there are
several things you can do.

First, you can always convert a C# string to a char* (pointer to an array of
char), in which the first null terminator becomes the end of the string. Of
course, this requires some unsafe code to do, but I mentioned it in case it
might come in handy at some point in the future.

Second, you can initialize the string by using IndexOf when initializing the
string:

string result = new string(Array.In dexOf(m_tHeader .m_sshortname, '0');

or if you have .Net 2.0:

string result = new string(Array.In dexOf<char>(m_t Header.m_sshort name, '0');

This overload will truncate the string you get at the first null 0. Of
course, you may have to check to see for sure whether there *is* a null zero
in the string, to prevent the third argument from being -1:

int index = Array.IndexOf<c har>(m_tHeader. m_sshortname, '0')
string result = new string(m_tHeade r.m_sshortname, 0, (index < 0 ? 0 :
index))

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer

Presuming that God is "only an idea" -
Ideas exist.
Therefore, God exists.
"claire" <so*****@micros oft.com> wrote in message
news:u5******** ******@TK2MSFTN GP10.phx.gbl...
I have a char[] that i convert to a string as follows
m_tHeader.m_ssh ortname is defined as char[8];

string result = new string(m_tHeade r.m_sshortname) ;

The problem is that any '\0' chars in the array remain in the string and
it's not terminated properly.

Is there a nice way to trim these off (string.trim doesnt work) rather
than my very nasty code below

while((result.L ength > 0)&&(result[result.Length - 1] == '\0'))

result = result.Remove(r esult.Length - 1,1);

thanks

Mar 21 '06 #2
claire wrote:
I have a char[] that i convert to a string as follows
m_tHeader.m_ssh ortname is defined as char[8];

string result = new string(m_tHeade r.m_sshortname) ;

The problem is that any '\0' chars in the array remain in the string and
it's not terminated properly.

Is there a nice way to trim these off (string.trim doesnt work)


Well, String.Trim does work - I suspect you're not using it properly.

Are you sure that the char array only has null characters at the end?
If so, just use:

string result = new string (m_tHeader.m_ss hortname).TrimE nd('\0');

That should work fine (and does in my test code).

Jon

Mar 21 '06 #3

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

Similar topics

5
13918
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 something like: char chars = "Hello!"; byte bytes = (byte) chars;
4
5393
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 "System.Text.Encoding.ASCII.GetString(bytearray)" of .Net library, we found that the char (delimiters) specified above are replaced with different char.
18
7952
by: Marcio Kleemann | last post by:
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...
3
2177
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 returns the index of the code in */ /* the LIBRARY structure if it is found. */ int findcode( LIBRARY *b, int n, char *tcode ) { int i;
2
10907
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 think for a sec. At first I read it as converting a 'const char *' to a 'std::string *' void f(const std::string &s) { std::cout << s.size() << "\n";
0
2029
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 Studio 2005). The problem occurred when I trying to opening and reading file: ============= C++ ============= void LoadSourceFile(char * fileName, unsigned char * data, int length)
2
4002
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 functions strtol, strtod, and strtoul, defined in <cstdlib>, convert a null- terminated character string to a long int, double, or unsigned long. You can use them to convert numeric strings of any base to a numeric
5
12647
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
3816
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 = strToChars(texts); String^ shiftcs = domainUpDown1->Text; char *shiftc = strToChars(shiftcs); int shift = atoi(shiftc); char *cipher = encCCipher(text, shift); String^ ciphers = gcnew String(cipher); textBox2->Text = ciphers;
4
3609
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. int WINAPI ImgSave(_T_Scan_Param *ScanP, unsigned char *szMicr, int *num_chars, int y0, int y1, int cOcrCode_option) struct _T_Scan_Param { char file1;
0
8683
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9170
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9031
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8901
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6528
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4371
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2336
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.