I've been looking for the past 30 minutes just on this one simple question but they all say to use Parse methods when I know they won't work because the string is possibly non-numeric. However, instead of just throwing an error I still want it to give out a number based on the string. Any ideas?
Asked
Active
Viewed 175 times
-2
-
1Will you please give some example strings and the expected output? Otherwise, we cannot answer effectively. – John Alexiou Oct 16 '21 at 00:53
-
How do you want to convert it? Do you want to get an int value by the length of the string for example? – alalalal Oct 16 '21 at 00:58
-
i would like to be able to put in any string and get some int out, be that the ascii values or something similar – Elgen T Oct 16 '21 at 01:26
-
If you want a string like "ABC" to be interpreted as `(int)'A' + (int)'B' + (int)'C'` (which is what I'm assuming you are talking about (from your comment below: _"Like I said above having it give me the raw ASCII values would work"_ (by the way, you didn't say that above)), then that's pretty easy to write. Something like `int total = 0; foreach (char chr in "ABC") { total += (int) chr; }` (this is just off the top of my head). That said, there's no way we'd know what you want unless you tell us – Flydog57 Oct 16 '21 at 02:24
2 Answers
1
If you just want a number based on the string, and you don't really care which number it is just as long as the string was used to create it, then GetHashCode() may be what you're looking for.
int num = str.GetHashCode();
If two strings are identical, then GetHashCode() will return the same number for both of them. If two strings are different, then it's very likely (but not guaranteed) that GetHashCode() will return different numbers for them.
BenM
- 434
- 3
- 7
0
Do you need any functionality beyond TryParse()?
if( double.TryParse(text, out double x))
{
// use numeric `x` here
}
or
if( int.TryParse(text, out int i))
{
// use integer `i` here
}
John Alexiou
- 26,060
- 8
- 73
- 128
-
yeah, i need it to work with strings that don't contain numbers. Like I said above having it give me the raw ASCII values would work – Elgen T Oct 16 '21 at 01:27
-
1@ElgenT - like I said to, please [edit] your question and add some examples. What kind of string and what kind of results do you expect. Without this information, you won't get any good answers. – John Alexiou Oct 16 '21 at 01:41
-
@ElgenT - you need to be more specific than "raw ASCII values". Even if we ignore the complexities of Unicode, each character has its own ASCII value. How should they combine into a single Int? – BenM Oct 16 '21 at 02:46