How to convert/parse from String to char in java?

文章推薦指數: 80 %
投票人數:10人

If you want to parse a String to a char, whereas the String object represent more than one character, you ... Resultsfromthe2022DeveloperSurveyarenowavailable Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore Howtoconvert/parsefromStringtocharinjava? AskQuestion Asked 10years,8monthsago Modified 1year,11monthsago Viewed 1.0mtimes 227 49 HowdoIparseaStringvaluetoachartype,inJava? Iknowhowtodoittointanddouble(forexampleInteger.parseInt("123")). IsthereaclassforStringsandChars? javastringparsingchar Share Follow editedMar24,2019at3:49 KeyMaker00 5,59711goldbadge4949silverbadges4949bronzebadges askedOct21,2011at18:09 RenRen 4,48688goldbadges3232silverbadges5757bronzebadges 4 YouwanttoparseaStringintoachararray?Pleasebemorespecific. – ZsomborErdődy-Nagy Oct21,2011at18:12 possibleduplicateofHowcanIconvertaStringtoachararray? – JohnFlatness Oct21,2011at18:12 1 YeahbutIdon'tseeanymethodinitthatwillhelpmechangeaStringsuchas"a"toacharsuchas'a' – Ren Oct21,2011at18:13 8 Idon'tthinkitisaduplicate.Iamtryingtojustconvertasingleletter. – Ren Oct21,2011at18:14 Addacomment  |  14Answers 14 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 323 IfyourstringcontainsexactlyonecharacterthesimplestwaytoconvertittoacharacterisprobablytocallthecharAtmethod: charc=s.charAt(0); Share Follow answeredOct21,2011at18:12 MarkByersMarkByers 770k176176goldbadges15431543silverbadges14341434bronzebadges 1 2 Formorethanonecharacter:char[]c=s.toCharArray(); – user3133925 Mar15,2019at13:28 Addacomment  |  73 Youcanusethe.charAt(int)functionwithStringstoretrievethecharvalueatanyindex.IfyouwanttoconverttheStringtoachararray,trycalling.toCharArray()ontheString. Stringg="line"; charc=g.charAt(0);//returns'l' char[]c_arr=g.toCharArray();//returnsalength4chararray['l','i','n','e'] Share Follow editedOct15,2018at21:37 answeredOct21,2011at18:12 GaʀʀʏGaʀʀʏ 4,21222goldbadges3838silverbadges5858bronzebadges 1 Well,true,althoughIwasseekingtoconvertasinglecharacterinastring,Iguessthatcouldworktoo. – Ren Oct21,2011at18:16 Addacomment  |  48 youcanusethistrick: Strings="p"; charc=s.charAt(0); Share Follow answeredOct21,2011at18:12 GenjuroGenjuro 7,08577goldbadges3636silverbadges6161bronzebadges 3 Butthatwillturn"123"into'1',isthatwhatyou'reafter? – aioobe Oct21,2011at18:19 1 Ididn'tmeantospecificallyuse"123".Iwasjustusingasanexample.Forcharitwouldbeadifferentexamplelike"p"sinceacharisasinglecharacter,notmultipleones. – Ren Oct21,2011at18:42 1 thetoCharArray()functionreturnsanarrayofcharsincaseyouwanttosplityourstringintochars – Genjuro May7,2013at8:27 Addacomment  |  11 Ifoundthisuseful: double-->Double.parseDouble(String); float-->Float.parseFloat(String); long-->Long.parseLong(String); int-->Integer.parseInt(String); char-->stringGoesHere.charAt(intposition); short-->Short.parseShort(String); byte-->Byte.parseByte(String); boolean-->Boolean.parseBoolean(String); Share Follow editedJul23,2020at6:44 jonrsharpe 107k2323goldbadges204204silverbadges380380bronzebadges answeredOct31,2017at3:28 HikhujHikhuj 14711silverbadge55bronzebadges 5 4 Whythumbsdown?Thisreallyanswerthequestion,soasyoucancheckhowtoparseinothertypes – Davide May5,2018at15:35 4 @DavideProbablybecausepostsshould'tincludetheimportantinformationasimagewhenitcanbepostedastext.Imagescan'tbesearchedandcopy/pasted,areoftenblockedandcan'tbereadbyusersrelyingonscreenreaders. – ModusTollens May5,2018at15:46 Pleaseedityourpostandshowtheactualtextinsteadofscreenshots.Otherscan'tcopyandpastefromyourimages.Seeherefordetails.Thankyou. – Pang Jun12,2018at2:29 3 Iagreewith@Davidequestion-"Whythumbsdown?".IbelievethatthiswillmaketheuserthatgotthisnottocontributewithstackoverflowinthefutureandIbelievethatthisshouldnotbethecase.Frommyperspective"thumbsdown"shouldnoteverbeused!It'snegativeinitsessenceanddoesn'tbringanyvalueatall. – Marco Aug28,2018at10:45 1 Areyousurethatchar-->StringGoesHere.parseFloat(intposition);iscorrect?HonestlyIhaven'tchecked,butI'mfairlysureStringdoesn'thaveaparseFloatmethod,andevenifitdoes,Ican'tseewhythatwouldbewhatyou'dbetryingtodothere. – BeUndead Mar18,2019at1:59 Addacomment  |  9 Ifthestringis1characterlong,justtakethatcharacter.Ifthestringisnot1characterlong,itcannotbeparsedintoacharacter. Share Follow answeredOct21,2011at18:13 VladVlad 34.3k66goldbadges7878silverbadges192192bronzebadges 3 Maybeahack,butcanbedone.Seestackoverflow.com/questions/21813888/build-char-from-string – Damo Feb16,2014at17:15 Yourstatementsayingthatastringlongerthan1charactercan'tbeparsedtoanintegeriswrong,seemyanswer. – AdamMartinu Dec14,2015at14:08 @Adam:Youransweriswrong,I'llexplaininacomment. – Vlad Dec14,2015at14:35 Addacomment  |  5 Stringstring="ThisisYasirShabbir"; for(charch:string.toCharArray()){ } orIfyouwantindividuallythenyoucanas charch=string.charAt(1); Share Follow answeredMay29,2016at12:00 YasirShabbirChoudharyYasirShabbirChoudhary 2,26822goldbadges2626silverbadges3030bronzebadges Addacomment  |  4 org.apache.commons.lang.StringEscapeUtils.(un)EscapeJavamethodsareprobabywhatyouwant Answerfrombrainzzynotmine: https://stackoverflow.com/a/8736043/1130448 Share Follow editedMay23,2017at12:34 CommunityBot 111silverbadge answeredJan5,2012at0:51 sinekonatasinekonata 34433silverbadges1111bronzebadges Addacomment  |  4 ThesimplestwaytoconvertaStringtoacharisusingcharAt(): StringstringAns="hello"; charcharAns=stringAns.charAt(0);//GivesYou'h' charcharAns=stringAns.charAt(1);//GivesYou'e' charcharAns=stringAns.charAt(2);//GivesYou'l' charcharAns=stringAns.charAt(3);//GivesYou'l' charcharAns=stringAns.charAt(4);//GivesYou'o' charcharAns=stringAns.charAt(5);//GivesYou::Exceptioninthread"main"java.lang.StringIndexOutOfBoundsException:Stringindexoutofrange:5 Hereisafullscript: importjava.util.Scanner; classdemo{ StringaccNo,name,fatherName,motherName; intage; staticdoublerate=0.25; staticdoublebalance=1000; ScannerscanString=newScanner(System.in); ScannerscanNum=newScanner(System.in); voidinput() { System.out.print("AccountNumber:"); accNo=scanString.nextLine(); System.out.print("Name:"); name=scanString.nextLine(); System.out.print("Father'sName:"); fatherName=scanString.nextLine(); System.out.print("Mother'sName:"); motherName=scanString.nextLine(); System.out.print("Age:"); age=scanNum.nextInt(); System.out.println(); } voidwithdraw(){ System.out.print("HowMuch:"); doublewithdraw=scanNum.nextDouble(); balance=balance-withdraw; if(balance<1000) { System.out.println("InvalidDataEntry\nBalancebelowRs1000notallowed"); System.exit(0); } } voiddeposit(){ System.out.print("HowMuch:"); doubledeposit=scanNum.nextDouble(); balance=balance+deposit; } voiddisplay(){ System.out.println("YourBalnce:Rs"+balance); } voidoneYear(){ System.out.println("Afteroneyear:"); balance+=balance*rate*0.01; } publicstaticvoidmain(Stringargs[]){ demod1=newdemo(); d1.input(); d1.display(); while(true){//Withdraw/Deposit System.out.println("Withdraw/DepositPressW/D:"); Stringreply1=((d1.scanString.nextLine()).toLowerCase()).trim(); charreply=reply1.charAt(0); if(reply=='w'){ d1.withdraw(); } elseif(reply=='d'){ d1.deposit(); } else{ System.out.println("InvalidEntry"); } //MoreManipulation System.out.println("WantMoreManipulations:Y/N:"); Stringmanipulation1=((d1.scanString.nextLine()).toLowerCase()).trim(); charmanipulation=manipulation1.charAt(0); System.out.println(manipulation); if(manipulation=='y'){} elseif(manipulation=='n'){ break; } else{ System.out.println("InvalidEntry"); break; } } d1.oneYear(); d1.display(); } } Share Follow editedNov20,2015at9:08 Vinz 5,89511goldbadge3131silverbadges5050bronzebadges answeredJul7,2013at15:05 IsabellaEngineerIsabellaEngineer 3,57311goldbadge1313silverbadges66bronzebadges Addacomment  |  3 IfyouwanttoparseaStringtoachar,whereastheStringobjectrepresentmorethanonecharacter,youjustsimplyusethefollowingexpression: charc=(char)Integer.parseInt(s). WheresequalstheStringyouwanttoparse.Mostpeopleforgetthatchar'srepresenta16-bitnumber,andthuscanbeapartofanynumericalexpression:) Share Follow answeredAug3,2014at14:55 AdamMartinuAdamMartinu 20311silverbadge1010bronzebadges 3 1 Thisiswrong.Parsingastringtoanumbermeansthatthenumberwasconvertedtoastring,andwewanttogetthenumberback.Exactlythesameway,parsingacharacterfromastringmeansthatthecharacterwasconvertedtoastring,andwewantthecharacterback.UsinganintermediatenumberisnotwhattheOPaskedabout. – Vlad Dec14,2015at14:38 @VladHedidaskforanumber,becausethat'swhatacharis,justlikeintanddouble.HeevengavetheexampleString"123".andwhosaysyoucan'tconvertachartoaStringwithalengthlargerthanone,andback?Tryityourselfwithcharc=123:String.valueOf((int)c).equals("123")returnstrue. – AdamMartinu Dec14,2015at18:12 1 Sorry,buteverythingboilsdowntothenumbers,that'snotthepointofthequestion.Youcanhavealookattheacceptedanswer,whichclearlyexcludesanintermediateint.Foryourexample,youneededtocasttoint,whichmeansthatyouareworkingnotwiththeoriginalchar,butwithanint,whichhappenstosomehowcorrespondtotheoriginalchar. – Vlad Dec14,2015at18:23 Addacomment  |  2 importjava.io.*; classss1 { publicstaticvoidmain(Stringargs[]) { Stringa=newString("sample"); System.out.println("Result:"); for(inti=0;i



請為這篇文章評分?