in persian/arabic character, some character used optional on top or bottom of other character like ِ َ ّ ُ.
in my example if i use this character, indexOf not found my word. consider that persian/arabic is rtl language.
for example:
منّم => م + ن + ّ + م
C#:
"منّم".IndexOf("من");
return -1
javascript:
var index= ' منّم '.indexOf('من');
console.log(index);
what happened in C#. anyone can explain this?
By passing in StringComparison.Ordinal as an argument to the overloaded String.IndexOf(), you could have also done the following:
"منّم".IndexOf("من", StringComparison.Ordinal); // returns 0
Specifying CompareOptions.Ordinal as an option should work, together with the IndexOf method of CompareInfo.
CompareInfo info = CultureInfo.CurrentCulture.CompareInfo;
string str = "منّم";
Console.WriteLine(info.IndexOf(str, "من", CompareOptions.Ordinal));
Output is 0.
DotNetFiddle if you want to try it yourself.
You should learn about the different methods that .Net uses to compare/match strings.
Best Practices for Using Strings in .NET
Some overloads with default parameters (those that search for a Char
in the string instance) perform an ordinal comparison, whereas others
(those that search for a string in the string instance) are
culture-sensitive. It is difficult to remember which method uses which
default value, and easy to confuse the overloads.
The section String Operations that Use the Invariant Culture gives a short explanation about combining characters.
Related
I have alphanumeric value = 106bd87f9386b63b. I want to convert this value into integer in c# and store the converted value into database. Is there any possibilities to convert it.
Did you try to use this:
the strLong is a declared variable.
and see this for your reference: https://learn.microsoft.com/en-us/dotnet/api/system.globalization.numberstyles?view=netframework-4.7.2
long.Parse(strLong, System.Globalization.NumberStyles.HexNumber);
You can do it with multiple methods choose one which is suitable to you
Method 1:
If you want to do it with Regex Here is Example helpful in Detail
C# Regular Expression to match letters, numbers and underscore
Here is also a useful and detailed link
Find and extract a number from a string
Other Methods:
You can also use Char.IsNumber('your character here')
here is Doc link of Microsoft
https://learn.microsoft.com/en-us/dotnet/api/system.char.isnumber?view=netframework-4.7.2
For the above method you have to split your string into characters and then check if it is character or not using Char.isNumber() Method .
Instead of all these you can also split this and make a function and match ASCII values and detect weather it is a number of not .
What ever method you use just detect number or not and concatinate it into a string and then at the end convert this string into a number using Convert class provided by Microsoft . Here is the detailed link of conversion
How can I convert String to Int?
I have a string input in the format of "string#int" and I want to convert it to "string-int" for web friendliness reasons for an api i am using.
To do this I could obviously just replace the single character # with a - using string.replace, but ideally I'd like to do a check that the input (which is user provided by the way) is in the correct format (string#int) while or before converting to the web friendly version with a "-" instead. Essentially I'm wondering if there is a method in C# that I could use to check that this input is in the correct format and convert it to the required result format.
There is no built-in way obviously, since the format you request is quite specific. Also, a string can contain anything, also a hastag, #, so I guess you need to narrow that down.
You could use regular expressions to check if the string is in the correct format. This would be possible expression:
[A-Za-z ]+#[0-9]+
Which matches for:
this is a string#123
There's nothing built in, but you could do the following:
var parts = input.Split(new char[] { '#' });
if (parts.Length != 2) incorrect format
int result;
if (!int.TryParse(parts[1], out result) incorrect format
output = String.Join("-", parts);
This takes the input and splits it on the "#" character. If the result isn't two parts then the string is invalid. You then check that the second part is an integer - if the TryParse fails it's not valid. The last step is to rejoin the two parts, but this time with a - as the separator.
I have this problem where String.Contains returns true and String.LastIndexOf returns -1. Could someone explain to me what happened? I am using .NET 4.5.
static void Main(string[] args)
{
String wikiPageUrl = #"http://it.wikipedia.org/wiki/ʿAbd_Allāh_al-Sallāl";
if (wikiPageUrl.Contains("wikipedia.org/wiki/"))
{
int i = wikiPageUrl.LastIndexOf("wikipedia.org/wiki/");
Console.WriteLine(i);
}
}
While #sa_ddam213's answer definitely fixes the problem, it might help to understand exactly what's going on with this particular string.
If you try the example with other "special characters," the problem isn't exhibited. For example, the following strings work as expected:
string url1 = #"http://it.wikipedia.org/wiki/»Abd_Allāh_al-Sallāl";
Console.WriteLine(url1.LastIndexOf("it.wikipedia.org/wiki/")); // 7
string url2 = #"http://it.wikipedia.org/wiki/~Abd_Allāh_al-Sallāl";
Console.WriteLine(url2.LastIndexOf("it.wikipedia.org/wiki/")); // 7
The character in question, "ʿ", is called a spacing modifier letter1. A spacing modifier letter doesn't stand on its own, but modifies the previous character in the string, this case a "/". Another way to put this is that it doesn't take up its own space when rendered.
LastIndexOf, when called with no StringComparison argument, compares strings using the current culture.
When strings are compared in a culture-sensitive manner, the "/" and "ʿ" characters are not seen as two distinct characters--they're processed into one character, which does not match the parameter passed in to LastIndexOf.
When you pass in StringComparison.Ordinal to LastIndexOf, the characters are treated as distinct, due to the nature of Ordinal comparison.
Another way to make this work would be to use CompareInfo.LastIndexOf and supply the CompareOptions.IgnoreNonSpace option:
Console.WriteLine(
CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(
wikiPageUrl, #"it.wikipedia.org/wiki/", CompareOptions.IgnoreNonSpace));
// 7
Here we're saying that we don't want combining characters included in our string comparison.
As a sidenote, this means that #Partha's answer and #Noctis' answer only work because the character is being applied to a character that doesn't appear in the search string that's passed to LastIndexOf.
Contrast this with the Contains method, which by default performs an Ordinal (case sensitive and culture insensitive) comparison. This explains why Contains returns true and LastIndexOf returns false.
For a fantastic overview of how strings should be manipulated in the .NET framework, check out this article.
1: Is this different than a combining character or is it a type of combining character? would appreciate if someone would clear that up for me.
Try using StringComparison.Ordinal
This will compare the string by evaluating the numeric values of the corresponding chars in each string, this should work with the special chars you have in that example string
string wikiPageUrl = #"http://it.wikipedia.org/wiki/ʿAbd_Allāh_al-Sallāl";
int i = wikiPageUrl.LastIndexOf("http://it.wikipedia.org/wiki/", StringComparison.Ordinal);
// returns 0;
The thing is C# lastindexof looks from behind.
And wikipedia.org/wiki/ is followed by ' which it takes as escape sequence. So either remove ' after wiki/ or have an # there too.
The following syntax will work( anyone )
string wikiPageUrl = #"http://it.wikipedia.org/wiki/Abd_Allāh_al-Sallāl";
string wikiPageUrl = #"http://it.wikipedia.org/wiki/#ʿAbd_Allāh_al-Sallāl";
int i = wikiPageUrl.LastIndexOf("wikipedia.org/wiki");
All 3 works
If you want a generalized solution for this problem replace ' with #' in your string before you perform any operations.
the ' characters throws it off.
This should work, when you escape the ' as \':
wikiPageUrl = #"http://it.wikipedia.org/wiki/\'Abd_Allāh_al-Sallāl";
if (wikiPageUrl.Contains("wikipedia.org/wiki/"))
{
"contains".Dump();
int i = wikiPageUrl.LastIndexOf("wikipedia.org/wiki/");
Console.WriteLine(i);
}
figure out what you want to do (remove the ', escape it, or dig deeper :) ).
I have file that match this pattern:
Name-003
Name-002
Name-001
Name0000
Name0001
Name0002
And I need a way to format a string to have this pattern.
If I use
string.Format("Name{0:0000}", index)
It give me:
Name-0003
Name-0002
Name-0001
Name0000
Name0001
Name0002
I need a way to specify the number of digit including the negative sign character.
I want a solution with String.Format()
You could look at the documentation for numeric formats (specifically the ; character):
string.Format("Name{0:0000;-000}", index)
... or you could learn how to use an if statement to select between two format strings based on the value of index.
I have some strings such as:
1.5555555555555
2.3421354325435354545
4.509019292
I want to format them into a string such as:
1.5555
2.3421
4.5090
I tried to use the C# String.Format but I can not get it to correctly work.
Can someone please give me the correct c# statement to accomplish this?
Thanks.
It's unclear if you'll always be dealing with numeric values. If you want to avoid parsing the strings as numbers, you might try something like this:
public static string TrimTo(string str, int maxLength)
{
if (str.Length <= maxLength)
{
return str;
}
return str.Substring(0, maxLength);
}
This will trim the provided string to six characters, if it's longer than six. This seems to be what you want, but (as Kees points out), will do something unexpected with a string like "1234567.890".
The conditional clause is necessary here because String.Substring will complain if the second index is outside of the string (if the string is shorter than maxLength, in other words).
(If you've played around with C# 3.0 extension methods at all, you might recognize this, slightly modified from the above, as an excellent opportunity for one: string trimmed = s.TrimTo(10);)
string.Format("{0:N4}",decimalValue);
Standard Numeric Format Strings
Custom Numeric Format Strings
If you convert the Strings to doubles you can use String.Format to specify how many decimal places you want to include when you reformat it as a String.
String.Format("{0:0.0000}", double.Parse("1.55555555555555"))