String to char array java - convert string to char - JournalDev

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

char[] toCharArray() : This method converts string to character array. · char charAt(int index) : This method returns character at specific index of string. keyboard_arrow_left Previous Next keyboard_arrow_right ShareonFacebook ShareonTwitter ShareonWhatsApp ShareonReddit ShareonLinkedIn ShareonEmail searchCoreJavaTutorial0.Java15Features1.Java14Features2.Java13Features3.Java12Features4.Java11Features5.Java10Features6.Java9Features7.Java8Features8.Java9Modules9.LambdaExpressions10.StreamAPI11.DateTimeAPI12.JavaAccessModifiers13.AbstractClassinJava14.InterfaceinJava15.CompositioninJava16.InheritanceinJava17.JavaNestedClasses18.JavaString19.JavaAnnotations20.JavaEnum21.CollectionsinJava22.JavaGenerics23.JavaScannerClass24.ExceptionHandling25.ThreadsinJava26.Synchronization27.JavaThreadLocal28.JavaTimer29.JavaThreadPool30.JavaCallableFuture31.JavaFutureTask32.JavaLock33.RegularExpressions34.JavaHeapMemory35.JVMMemoryModel36.JavaReflectionAPI37.SerializationinJava38.JavaSystemClass39.Internationalization40.ThreadDump41.DeadlocksinJava42.JDK,JREandJVM43.JavaClassloaderSometimeswehavetoconvertStringtothecharacterarrayinjavaprogramsorconvertastringtocharfromspecificindex.StringtocharJava Stringclasshasthreemethodsrelatedtochar.Let’slookatthembeforewelookatajavaprogramtoconvertstringtochararray.char[]toCharArray():Thismethodconvertsstringtocharacterarray.Thechararraysizeissameasthelengthofthestring.charcharAt(intindex):Thismethodreturnscharacteratspecificindexofstring.ThismethodthrowsStringIndexOutOfBoundsExceptioniftheindexargumentvalueisnegativeorgreaterthanthelengthofthestring.getChars(intsrcBegin,intsrcEnd,chardst[],intdstBegin):Thisisaveryusefulmethodwhenyouwanttoconvertpartofstringtocharacterarray.Firsttwoparametersdefinethestartandendindexofthestring;thelastcharactertobecopiedisatindexsrcEnd-1.ThecharactersarecopiedintothechararraystartingatindexdstBeginandendingatdstBegin+(srcEnd-srcBegin)–1.Let’slookatasimplestringtochararrayjavaprogramexample. packagecom.journaldev.string; publicclassStringToCharJava{ publicstaticvoidmain(String[]args){ Stringstr="journaldev"; //stringtochararray char[]chars=str.toCharArray(); System.out.println(chars.length); //charatspecificindex charc=str.charAt(2); System.out.println(c); //Copystringcharacterstochararray char[]chars1=newchar[7]; str.getChars(0,7,chars1,0); System.out.println(chars1); } } Inaboveprogram,toCharArrayandcharAtusageisverysimpleandclear.IngetCharsexample,first7charactersofstrwillbecopiedtochars1startingfromitsindex0.That’sallforconvertingstringtochararrayandstringtocharjavaprogram.Reference:APIDoc ShareonFacebook ShareonTwitter ShareonWhatsApp ShareonReddit ShareonLinkedIn ShareonEmail PrevJavaStringsplit NextWhatisJavaStringPool? Pankaj IloveOpenSourcetechnologiesandwritingaboutmyexperienceaboutthemismypassion.FollowAuthor Comments Morphatsays: May18,2020at11:38amWhyisitthatificonvertastringwithaspacebetweenwords,itonlyrecognizesthefirstwordandconvertsthattoachararray.Isthereawayaroundit? Pankajsays: May18,2020at11:47pmNotsurewhatisyourissue,butitworksfinewithaspaceinthestring. jshell>Strings="Hello"; s==>"Hello" jshell>s.toCharArray(); $2==>char[5]{'H','e','l','l','o'} jshell>Strings="Helloworld"; s==>"Helloworld" jshell>s.toCharArray(); $4==>char[11]{'H','e','l','l','o','','w','o','r','l','d'} jshell> M.kingdashtisays: October7,2019at6:55amwhatarethememberofclass? Ismethodsanddatavariablearethememberofaclass? Maheshsays: March17,2019at6:52amIfaStringvalueis“10”,toCharArrayreturnsvalue01insteadofthe10…anyreasonforthis? Pankajsays: March17,2019at7:07amCanyoushareyourcode?Hereitisfromjshellanditlooksperfect. jshell>Strings="10"; s==>"10" jshell>s.toCharArray(); $2==>char[2]{'1','0'} VictrYaosays: December29,2018at7:09am… //Copystringcharacterstochararraystr.getChars(chars1,0);Thisoverloadedmethodmightjustworkaswell? JeThousays: June26,2018at6:50amDoesthelastofcharacterarrayisanullornot? Nareshsays: December11,2014at11:52pmIjustlookedtheStringinterviewquestions,Iamgettingsoointerestingtostudytheholetutorial.ItsNice.Commentsareclosed. close Genericselectors Exactmatchesonly Exactmatchesonly Searchintitle Searchintitle Searchincontent Searchincontent SearchinexcerptPostTypeSelectors Hidden



請為這篇文章評分?