User interview question: C #, do not use any parse, tryparse, convert method, the self-writing function converts the number string to an integer

Source: Internet
Author: User

There are two simple methods,

1. Don't use tryparse, so you can write one yourself:

Using system; Class test {static void main () {string S1 = console. readline (); int I; If (mytryparse (S1, out I) {console. writeline ("succeeded:" + I);} else {console. writeline ("failed: enter a number! ") ;}} Static bool mytryparse (string S, out int I) {try {int temp = convert. toint32 (s);} catch {I =-1; return false;} If (convert. toint32 (s)> = 0 | convert. toint32 (s) <0) {I = convert. toint32 (s); Return true ;}else {I =-1; return false ;}}}

Second: Use the method provided by laoliu, a netizen, and draw on the advantages of JavaScript parseint () to enrich laoliu'sCode:

Using system; Class test {static void main () {console. writeline (s2i (console. readline ();} static int s2i (string s) {char [] C1 = S. tochararray (); int result = 0; For (INT I = 0; I <c1.length; I ++) {If (c1 [I]> = 48 & c1 [I] <= 57) Result = (result * 10) + c1 [I]-'0'; elsecontinue ;} return result ;}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.