String character array - c#

Isn't a string already a character array in c#? Why is there a explicit ToCharacterArray function? I stumbled upon this when I was looking upon ways to reverse a string and saw a few answers converting the string to a character array first before proceeding with the loop to reverse the string. I am a beginner in coding.
Sorry if this seems stupid, but I didn't get the answer by googling.

Isn't a string already a character array in c# ?
The underlying implementation is, yes.
But you are not allowed to directly access that. String is using encapsulation to be an immutable object.
The actual array is private and hidden from view. You can use an indexer (property) to read characters but you cannot change them. The indexer is read only.
So yes, you do need ToCharacterArray() for reversing and similar actions. Note that you always end up with a different string, you cannot alter the original.

Isn't a string already a character array in c# ?
No, a string is a CLASS that encapsulates a "sequential collection of characters" (see Docs). Notice it doesn't explicitly say an "Array of Char". Now, it may be true that the string class currently uses a character array to accomplish this, but that doesn't mean it ~must~ use a character array to achieve that end. This is a fundamental concept of Object Oriented Programming that combines information hiding and the idea of a "black box" that does something. It doesn't matter how the black box (class) accomplishes its task under the hood, as long is it doesn't change the public interface presented to the end user. Perhaps, in the next version of .Net, some new-fangled magical structure that is not an array of characters will be used to implement the string class. The end user may not be aware that this change has even occurred because they can still use the string class in the same way, and if they so desire, could still output the characters to an array with ToCharArray()...even though internally the string is no longer an array of characters.

Yes String type is a character array but string array is not an character array you must have to convert each string in your array in char type so that you can easily reverse its indexes and then convert it into temporary string and then add that string to array to be reversed

Internally, the text is stored as a sequential read-only collection of Char objects.
See Programming Guide Docs

Console.WriteLine(StringHelper.ReverseString("framework"));
Console.WriteLine(StringHelper.ReverseString("samuel"));
Console.WriteLine(StringHelper.ReverseString("example string"));
OR
public static string ReverseString(string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}

Related

Parsing a string to get a specific value

I'm new to C#. I'm parsing for a lot number in a 2D barcode. The actual lot number 'A2351' is hidden in this barcode string "+M727PP011/$$3201001A2351S". I would like to break this barcode up in separate string blocks but the delimiters are not consistent.
The letter prefix in front of the 4 digit lot number can be a 'A', 'P', or a 'D' There is a single letter following the lot number that can be ignored.
string Delimiter = "/$$3";
//barcode format:M###PP###/$$3 ddmmyy lotnumprefix 'A' followed by lotNum
string lotNum= "+M727PP011/$$3201001A2351S";
string[] split = lotNum.Split(new[] {Delimiter}, StringSplitOptions.None);
How do I extract the lot number after the date?
Based on your initial example and then the subsequent edit in which you showed how you are solving this, it sounds like the lot number is always in the same place. It would be cleaner (and more in line with standard C# code) to use a single call to string.Substring(int,int) rather than the two lines you are using which also require pulling in the VB library. You just need to call Substring and give it the starting index and the length.
So this code:
string lotNum = Strings.Right(barcode, 6);
lotNum = lotNum.Remove((lotNum.Length - 1), 1);
Can be done with this single substring call:
string lotNum = barcode.Substring(barcode.Length - 6, 5);
Edit
Just further clarification on why it might be better to use the call to Substring. In C# string objects are immutable. That means that when you make the call to Strings.Right you are getting back a new string object. When you then call lotNum.Remove you do not "remove" a character from the existing string, a new string is allocated with the character(s) removed and is returned to you. So with your code there are two new string allocations when trying to extract the lot number. When you make the call to Substring you will get back a new string, but instead of getting a new string that you immediately then modify and get a second new string, you will only need to allocate one new string to extract the lot number. In the example you have given there probably would not be any noticeable performance/memory issue, but it is something that could potentially lead to trouble if this code was in a tight loop or something like that.
If you're just trying to get the lot number, it's really dependent on the format of the input string (is it a consistent length, are there any reliable prefixes/suffixes relative to the data you're trying to parse that you can reference from, etc). It looks like your data is definable by its static position in the string, so it looks like you could use the substring
(with an index of 20?) method to accomplish what you want.

Replace control character in string c#

Some text fields in my database have bad control characters embedded. I only noticed this when trying to serialize an object and get an xml error on char  and . There are probably others.
How do I replace them using C#? I thought something like this would work:
text.Replace('\x2', ' ');
but it doesn't.
Any help appreciated.
Strings are immutable - you need to reassign:
text = text.Replace('\x2', ' ');
exactly as was said above, strings are immutable in C#. This means that the statement:
text.Replace('\x2', ' ');
returned the string you wanted,but didn't change the string you gave it. Since you didn't assign the return value anywhere, it was lost. That's why the statement above should fix the problem:
text = text.Replace('\x2', ' ');
If you have a string that you are frequently making changes to, you might look at the StringBuilder object, which works very much like regular strings, but they are mutable, and therefore much more efficient in some situatations.
Good luck!
-Craig
The larger problem you're dealing with is the XmlSerialization round trip problem. You start with a string, you serialize it to xml, and then you deserialize the xml to a string. One expects that this always results in a string that is equivalent to the first string, but if the string contains control characters, the deserialization throws an exception.
You can fix that by passing an XmlTextReader instead of a StreamReader to the Deserialize method. Set the XmlTextReader's Normalization property to false.
You should also be able to solve this problem by serializing the string as CDATA; see How do you serialize a string as CDATA using XmlSerializer? for more information.

Is string.ToCharArray() necessary for enumerating?

Why on Earth would someone convert a string to a char[] before enumerating the characters in it? The regular pattern for initializing a System.Security.SecureString found all around the net follows:
SecureString secureString = new SecureString();
foreach (char c in "fizzbuzz".ToCharArray())
{
secureString.AppendChar(c);
}
Calling ToCharArray() makes no sense for me. Could someone tell whether I am wrong here?
Since string implements IEnumerable<char>, it's not necessary in this context. The only time you need ToCharArray is when you actually need an array.
My guess is that most people who call ToCharArray don't know that string implements IEnumerable (even though as far as I know it always has).
Actually that is bad because it
enumerates on the string
creates an array with a copy of all chars
enumerates on that
A lot of unnecessary work...
That's because strings are immutable, and giving out a pointer to its internal array is not allowed, so ToCharArray() makes a copy instead of a cast.
That is:
you can enumerate a string as a char[] but:
you cannot:
var chars = (char[])"string";
If you would go enumerating and would want to break at some point, by using the toCharArray() would already have enumerated the whole string nad made a copy of all chars. If the string would be very big, that is quite expensive...

Fixed string size in C#

The short question:
Is it possible to create a fixed size string in C#?
I know that in VB it's possible declaring something like this: str AS string * 20
The long story:
I need to read a binary file that contains a 20 byte field into a string. I read the content of the file into an object (class). I want to limit the strings in the object in the class definition.
Thank you very much for your concern.
roi
You could declare and fill a fixed size char array, and then pass that to the String objects constructor to make the string from that.
var newString = new string(theCharArray);
You should create a property of type string that checks value.Length in the setter and truncates it or throws an exception.
You should use 'StringBuilder' for your issue.
Try using the VBFixedString attribute. This is an information-only attribute and does not restrict the actual length of the string. It is used for communicating with API calls that expect a VB6-style fixed-length string. See http://msdn.microsoft.com/en-us/library/x14b6s77.aspx

c# convert string that has ctrl+z to regular string

i have a string like this:
some_string="A simple demo of SMS text messaging." + Convert.ToChar(26));
what is the SIMPLEST way of me getting rid of the char 26?
please keep in mind that sometimes some_string has char 26 and sometimes it does not, and it can be in different positions too, so i need to know what is the most versatile and easiest way to get rid of char 26?
If it can be in different positions (not just the end):
someString = someString.Replace("\u001A", "");
Note that you have to use the return value of Replace - strings are immutable, so any methods which look like they're changing the contents actually return a new string with the appropriate changes.
If it's only at the end:
some_string.TrimEnd((char)26)
If it can be anywhere then forget this and use Jon Skeet's answer.

Categories