i have a string strText with certain value on it,i need to assign '\0' or charactor at the specified position of strText.
ie strText[5]='\0'.how is it possible in c#.
You can use the Insert method to specify the index. You need to give it a string though, so if you can replace '\0' with "\0" or else just call .ToString()
strText = strText.Insert(5, yourChar.ToString());
Strings are immutable, so you will need to convert it to a character array, set the character at the specified position, and then convert back to string:
char[] characters = "ABCDEFG".ToCharArray ();
characters[5] = '\0';
string foo = new String (characters);
Related
I was trying to remove last part of a string but failed.Here string named D:\software\VS2012\newtext.txt and i want to trim last section of string so here newtext.txt . I should get D:\software\VS2012 but how to do it in c#.When i tried it is removing all the string that has '\'. Here is what i did in c#
string str = #"D:\softwares\VS2012\newtext.txt";
str= str.Remove(str.IndexOf('\\'));
Console.WriteLine(str);
There is a premade function for this in the framework
string str = #"D:\softwares\VS2012\newtext.txt";
string path = System.IO.Path.GetDirectoryName(str);
(Reference)
Note that your original code does not work because you are removing from the first backslash, not the last. Substitute this line to make your code work
str = str.Remove(str.LastIndexOf('\\'));
Try using System.IO.Path.GetDirectoryName(string):
string dirname= System.IO.Path.GetDirectoryName(#"D:\softwares\VS2012\newtext.txt");
For removing a known portion of a string you can simply use the Replace.
In your case:
str = str.Replace("\\newtext.txt", ""); //this will give you the same result of the System.IO.Path.GetDirectoryName already suggested by gmiley, but it's more in a string context as per your question
Though if you want to remove the last part of a string by the last encounterd known character then the suggested "LastIndexOff('\')" method already suggested along with the Remove.
If you want to use a delimiter method, so depending on the delimiter character but not on the string format (in your case path format) the LastIndexOff(char) is the best option.
Although you could also split the string into an array and then rejoin the array after removing the last element:
var delmimter = '\\';
var strAy = str.Split(char);
str = String.Join('\\', strAy.SkipLast(1).ToArray());
With this method you don't need to rely on the existence of the delimiter char in the string and the result is always without the delimiter char at the end.
Besides, you can easily create an extension with the delimiter as a parameter.
We should check the existance of the char also
string str = #"D:\softwares\VS2012\newtext.txt";
int rstr = str.LastIndexOf('\\');
if (rstr>0) str= str.Remove(rstr);
Console.WriteLine(str);
I have a six digit unicode character, for example U+100000 which I wish to make a comparison with a another char in my C# code.
My reading of the MSDN documentation is that this character cannot be represented by a char, and must instead be represented by a string.
a Unicode character in the range U+10000 to U+10FFFF is not permitted in a character literal and is represented using a Unicode surrogate pair in a string literal
I feel that I'm missing something obvious, but how can you get the follow comparison to work correctly:
public bool IsCharLessThan(char myChar, string upperBound)
{
return myChar < upperBound; // will not compile as a char is not comparable to a string
}
Assert.IsTrue(AnExample('\u0066', "\u100000"));
Assert.IsFalse(AnExample("\u100000", "\u100000")); // again won't compile as this is a string and not a char
edit
k, I think I need two methods, one to accept chars and another to accept 'big chars' i.e. strings. So:
public bool IsCharLessThan(char myChar, string upperBound)
{
return true; // every char is less than a BigChar
}
public bool IsCharLessThan(string myBigChar, string upperBound)
{
return string.Compare(myBigChar, upperBound) < 0;
}
Assert.IsTrue(AnExample('\u0066', "\u100000));
Assert.IsFalse(AnExample("\u100022", "\u100000"));
To construct a string with the Unicode code point U+10FFFF using a string literal, you need to work out the surrogate pair involved.
In this case, you need:
string bigCharacter = "\uDBFF\uDFFF";
Or you can use char.ConvertFromUtf32:
string bigCharacter = char.ConvertFromUtf32(0x10FFFF);
It's not clear what you want your method to achieve, but if you need it to work with characters not in the BMP, you'll need to make it accept int instead of char, or a string.
As per the documentation for string, if you want to iterate over characters in a string as full Unicode values, use TextElementEnumerator or StringInfo.
Note that you do need to do this explicitly. If you just use ordinal values, it will check UTF-16 code units, not the UTF-32 code points. For example:
string text = "\uF000";
string upperBound = "\uDBFF\uDFFF";
Console.WriteLine(string.Compare(text, upperBound, StringComparison.Ordinal));
This prints out a value greater than zero, suggesting that text is greater than upperBound here. Instead, you should use char.ConvertToUtf32:
string text = "\uF000";
string upperBound = "\uDBFF\uDFFF";
int textUtf32 = char.ConvertToUtf32(text, 0);
int upperBoundUtf32 = char.ConvertToUtf32(upperBound, 0);
Console.WriteLine(textUtf32 < upperBoundUtf32); // True
So that's probably what you need to do in your method. You might want to use StringInfo.LengthInTextElements to check that the strings really are single UTF-32 code points first.
From https://msdn.microsoft.com/library/aa664669.aspx, you have to use \U with full 8 hex digits. So for example:
string str1 = "\U0001F300";
string str2 = "\uD83C\uDF00";
bool eq = str1 == str2;
using the :cyclone: emoji.
I have a split string,
string s = Console.ReadLine();
string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
s should receive input like this:
string literal, numeric value, numeric value, numeric value OR string literal
I realize that all this input gets read as a string, but I'm trying to validate the numbers in the string (checking for >0), as well as assign each value in the string to a variable. What would be the best way to go about this?
You're looking for a specific pattern. I'd suggest to use a regex, and then get the number groups - and do the > 0 validation check.
string s = Console.ReadLine();
string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
string stringValue0 = values[0];
int numericValue1 = int.Parse(value[1]); // Assuming the value is an valid interger.
int numericValue2 = int.Parse(value[2]); // Assuming the value is an valid interger.
int numericvalue3;
string stringValue3;
if (!int.TryParse(values[3], out numericValue3) // Trying to convert the text to an interger. If it fails, assign it to the stringValue3.
stringValue3 = values[3];
You can always use int.TryParse to validate if a text contains a number.
static void Main(string[] args)
{
string str_val = "8584348,894";
//int prefix = Convert.ToInt32(str_val[0]); //prefix = 56 O_o
//int prefix = (int)str_val[0]; //what, again 56? i need 8!
int prefix = Convert.ToInt32("8"); //at least this works -_-
}
Any idea how to convert first symbol to right numeric value?
If you use:
Convert.ToInt32(str_val[0]);
then you are actually calling the overload:
Convert.ToInt32(char val);
which gives the Unicode/Ascii number of character being passed as a parameter.
If you want to convert first character, you need to force it to be a string type:
Convert.ToInt32(str_val.Substring(0, 1));
This way you call the overload:
Convert.ToInt32(string val);
which actually do what you want (convert string value to int value that this string represents).
Your trying to parse a string but passing in a char. Convert the character to a string first.
int prefix = Convert.ToInt32(str_val[0].ToString());
So the character value of 8 is the ASCII value 56, what you want to do is inteprete the value as a string rather than an ASCII Value. By using the .ToString() method you are converting the character into a null terminated string, which can be read by the ToInt32 method.
By doing this way Convert.ToInt32(str_val[0]) you are reading the character at a index of the string that converts the char to int. the int is the ascii for it
Like Bridge mentioned, it's getting the ASCII value. When you use the indexer on the string class to get just a character, it returns it as a char. If you read the char documentation you'll see that it is internally stored as a numeric UTF-16 value. It also has implicit conversions to and from most numeric types, which extract the UTF-16 value, or convert the numeric form into the character form. That's what you're doing.
What you mean to do is parse it as an int, not get the numeric representation of the UTF-16 value. That's where the Convert answers all come in.
Int32.Parse(str_val[0])
Will give you number in string.
How I set new value for an string by index value?
I tried:
string a = "abc";
a[0] = "A";
not works for strings, but yes for chars. Why?
Strings in C# (and other .NET languages which use System.String in the base class library) are immutable. That is, you can't modify a string character by character that way (or for that matter, can you modify a string ever).
If you want to modify a string based on the index, you have to convert it to an array using System.String.ToCharArray() first. You convert it back to a string using System.String's constructor, passing in the modified array.
Your example would have to be changed to look like:
string a = "abc";
char[] array = a.ToCharArray();
array[0] = 'A'; //Note single quotes, not double quotes
a = new string(array);
The System.String type does not permit writing by index (or via any means -- to change a the content of a String variable, one must replace it with a reference to an entirely new String). The System.Text.StringBuilder type does, however, permit writing by index. One may create a new System.Text.StringBuilder object (optionally passing a string to the constructor), manipulate it, and then use its ToString method to convert it back to a string.
A replacement would be this:
string a = "abc";
a = a.Remove(0, 1);
a = a.Insert(0, "A");
or for the C say:
string a = "abc";
a = a.Remove(2, 1);
a = a.Insert(2, "C");
Also using a stringbuilder may work as per http://msdn.microsoft.com/en-us/library/362314fe.aspx
StringBuilder sb = new StringBuilder("abc");
sb[0] = 'A';
sb[2] = 'C';
string str = sb.ToString();
Use StringBuilder if you need a mutable String.
Also: a[0] can represent one character while "A" is a String object-it is illegal.
a[0] for a character is a address in memory to which you can assign a value.
string on the other hand is a class and in this case the a[0] is actually a function call to the overloaded operator[]. You can't assign values to functions.