Int32.TryParse equivalent for String? - string

I have been doing some homework. The task was to implement System.Int32.TryParse to check if an entered value is a number or something random. I was wondering if there is a built-in method that checks if something entered is a letter and NOT a number. I tried searching google and MSDN in the string type, but with no luck so far. I did write my own implementation, but I was curious.
Tnx

The easiest way to check whether a character is a number is probably to check whether it is in range from '0' to '9'. This works because of the way characters are encoded - the digits are encoded as a sub-range of the char values.
let str = "123"
let firstIsNumber =
str.[0] >= '0' && str.[0] <= '9'
This gives you a bit different behavior than Char.IsDigit because Char.IsDigit also returns true for thigns that are digits in other alphabets, say ႐႑႒႓႔႕႖႗႘႙ I suspect you do not plan to parse those :-).

Related

Check if string contains 2 numbers

if PassField.Text:match("%a+%d%d+") or PassField.Text:match("%d%d+%a+") then
PWValid = true
else
return 'Error1'
end
This is my code so far but it's not too efficent because the string can be like bb1b12 so i would need to detect if the string contains 2 numbers anywhere
Two numbers is "some digits, then some non-digits, then some more digits". You don't need to care about anything else in string. Just use %d compliment - %D - it means exactly opposite of original. Also you probably should use find if you only want to test if string is valid or not.
str:find("%d+%D+%d+")

Convert String of words/letters into an Integer

Today I've finally decided to make an account, in hope for some aid in an issue I've spent the last few hours hunting. (I've spent the past couple hours hunting down a response, from Google to here to Unity Answers. Here's everything that I've found so far, which doesn't work.)
What I'm looking for, is to change a string of purely words/letters into an integer. Therefore "Hello World", would be translated into a string of numbers accordingly. This may be surprising, but this is a lot harder than it sounds. I've found a way to do essentially everything but, thus far.
Presumably the best way would be to get the ASCII value of each letter in the string, and put them all together into a single integer. (No sequences or need to separate them, but one single number.) I have no idea where to get started or how to do that, however. Really anything that you think would work, preferably as short-hand and un-bothersome as possible.
To be as clear as possible, I need to take the letter-only variable "example" and transmorph it to be a integer/only a sequence of numbers.
If you're just trying to convert an arbitrary string into a random seed, then why not try randomSeed.GetHashCode()? That will return an int value suitable for setting the seed, which would produce the same number each time the same string is entered.
You can iterate over all characters, get their charCode and chain them together. The first method splits the string into single chars and uses Array.reduce:
var str = 'qwertzuiop';
var num = parseInt(str.split('').reduce(function(a, b) {return a + b.charCodeAt(0);}, '');
The second calls Array.forEach on the string, because it has numerical indices and a length property.
var num = ''; [].forEach.call(str, function(c) {num += c.charCodeAt(0);});
num = parseInt(num);
In stoneaged browsers you have to use for-loops instead.

intval($var) == strval($var) returns true

the given example is really simple so I don't think it needs any explaining.
I couldn't find any references on the docs that can explain this behaviour and I've also found a couple workarrounds for this, so you don't really need to bother finding them (thanks in advance though).
I'd just really like if some1 could explain this..... doesn't make any sense to me:
// comma separated IDs to later use in SQL statement
$var = '10,20,30,40,743,102394';
$multi_intval = intval($var); // same with (int) $var
$multi_string = strval($var); // same with (string) $var
var_dump($multi_intval, $multi_string, $multi_intval == $multi_string);
// result
int(10) string(22) "10,20,30,40,743,102394" bool(true)
how is 10 equal to a 22 strlen string?
I just ran across this looking for another answer, so even though it is old Ill give an answer in case someone else comes across it.
From the php docs here: If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number
Because of this your comparison intval($var) == strval($var) is changed to something like intval($var) == intval(strval($var)) which is of course equal (I don't know what the language is using to change the string to an integer, the above is just visual representation). If you really need to know if they are identical, use ===.

Extract decimal part in a string in C#

I have a string in which the data is getting loaded in this format. "float;#123456.0300000" from which i need to extract only 123456.03 and trim all other starting and ending characters. May be it is very basic that i am missing, please let me know how can i do that. Thanks.
If the format is always float;# followed by the bit you want, then it's fairly simple:
// TODO: Validate that it actually starts with "float;#". What do you want
// to do if it doesn't?
string userText = originalText.Substring("float;#".Length);
// We wouldn't want to trim "300" to "3"
if (userText.Contains("."))
{
userText = userText.TrimEnd('0');
// Trim "123.000" to "123" instead of "123."
if (userText.EndsWith("."))
{
userText = userText.Substring(0, userText.Length - 1);
}
}
But you really need to be confident in the format - that there won't be anything else you need to remove, etc.
In particular:
What's the maximum number of decimal places you want to support?
Might there be thousands separators?
Will the decimal separator always be a period?
Can the value be negative?
Is an explicit leading + valid?
Do you need to handle scientific format (1.234e5 etc)?
Might there be trailing characters?
Might the trailing characters include digits?
Do you need to handle non-ASCII digits?
You may well want to use a regular expression if you need anything more complicated than the code above, but you'll really want to know as much as you can about your possible inputs before going much further. (I'd strongly recommend writing unit tests for every form of input you can think of.)
Why not just do:
String s = "float;#123456.0300000";
int i = int.Parse(s.Substring(s.IndexOf('#') + 1));
I haven't tested this, but it should be close.
Assuming the format doesn't change, just find the character after the '#' and turn it into an int, so you lose everything after the '.'.
If you need it as a string, then just call the ToString method.

function to confirm the presence of both letters and numbers/ Ignoring excedents

So, I'm trying to build up a program with MATLAB according to some indications from my teacher and I came up with some obstacles which would give me a better grade if I could get them right. Here they are:
The user is asked to insert a string but it can't have more than 20 characters. If it does, the excedents will be ignored and the string is saved with the first 20 characters the user inserted. How do I ignore the excedents in a string and save it anyway?
isletter is a function that tells us if the elements are all letters. In this program, the user is asked to insert a string that needs to include both numbers and letters, so that strings with just letters or just numbers are excluded, and then I'll use a while to keep asking for a string with these characteristics.
Could you please help me? This is my first semester with MATLAB. Thank you!
If you want to disallow characters other than letters and numbers (i.e. '/#!' or whitespace) and require that the string they enter has to have at least 1 letter and 1 number, then you can use the ISSTRPROP function (which is more general than ISLETTER) to check for other types of characters. The idea to use INPUTDLG to prompt for the string (as suggested in Aabaz's answer) is a good one, so here's a nice condensed solution using INPUTDLG that achieves what you want:
answer = ''; %# Initialize answer to be an empty string
while any(~isstrprop(answer, 'alphanum')) || ... %# Check for alphanumeric chars
~any(isletter(answer)) || ... %# Check for at least 1 letter
~any(isstrprop(answer, 'digit')) %# Check for at least 1 number
answer = inputdlg('Enter string:'); %# Prompt for input
answer = answer{1}(1:min(20, end)); %# Trim answer to max of 20 chars
end
Note how the functions MIN and END are used to trim the string to 20 characters.
For the first part of your problem you can use the Matlab function inputdlg which prompts a dialog box asking for user input. Then you can trim the input as you like.
For the second part of your problem the function isletter that you mentioned will tell you for each character individually if they are alphabetic letters, so you could sum that result and check if it is between 1 and 19 for example. That will tell you that your string contains both letters and numbers.
Finally, you can put your code inside a while loop and change a variable when your conditions are met so that you can break outside of the loop.
This example code demonstrates this:
tryagain=1;
while(tryagain)
answer=inputdlg('Insert a 20 character string that contains both letters and numbers','User input');
answer=answer{1};
if(numel(answer)>20)
answer=answer(1:20);
end
letters=sum(isletter(answer));
numbers=sum(~arrayfun(#(x)isempty(str2num(x)),answer));
if(letters>0 && numbers>0)
tryagain=0;
end
end

Resources