C# | Arrays of Strings - GeeksforGeeks
文章推薦指數: 80 %
C# | Arrays of Strings ... declares & initializes string array String[] s1 = new String[2]; // assign the value "Geeks" in array on its ... Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryMust-DoCodingQuestionsExploreMoreForStudentsLIVECompetitiveProgrammingDataStructureswithC++DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsContestsandEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblems ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningHTMLSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesC#|HowtogetallelementsofaListthatmatchtheconditionsspecifiedbythepredicateC#|Array.FindAll()MethodC#|Array.Find()MethodC#|String.IndexOf()Method|Set–1C#|Substring()MethodString.Split()MethodinC#withExamplesC#|ArraysofStringsC#|ArraysC#|StackClassC#StackwithExamplesC#QueuewithExamplesLinkedListImplementationinC#C#|LinkedListClassC#|ListClassC#|HowtocheckwhetheraListcontainsaspecifiedelementC#|HowtocheckwhetheraListcontainstheelementsthatmatchthespecifiedconditionsC#|CheckifanarraycontaintheelementsthatmatchthespecifiedconditionsC#|CheckwhetheranelementiscontainedintheArrayListC#|GetorsettheelementatthespecifiedindexinArrayListC#|GetsorSetstheelementatthespecifiedindexintheListC#|IsNullOrEmpty()MethodDifferencebetweenAbstractClassandInterfaceinC#C#DictionarywithexamplesC#|MethodOverridingDifferentwaystosortanarrayindescendingorderinC#C#|IsNullOrWhiteSpace()MethodDifferencebetweenRefandOutkeywordsinC#C#|HowtogetallelementsofaListthatmatchtheconditionsspecifiedbythepredicateC#|Array.FindAll()MethodC#|Array.Find()MethodC#|String.IndexOf()Method|Set–1C#|Substring()MethodString.Split()MethodinC#withExamplesC#|ArraysofStringsC#|ArraysC#|StackClassC#StackwithExamplesC#QueuewithExamplesLinkedListImplementationinC#C#|LinkedListClassC#|ListClassC#|HowtocheckwhetheraListcontainsaspecifiedelementC#|HowtocheckwhetheraListcontainstheelementsthatmatchthespecifiedconditionsC#|CheckifanarraycontaintheelementsthatmatchthespecifiedconditionsC#|CheckwhetheranelementiscontainedintheArrayListC#|GetorsettheelementatthespecifiedindexinArrayListC#|GetsorSetstheelementatthespecifiedindexintheListC#|IsNullOrEmpty()MethodDifferencebetweenAbstractClassandInterfaceinC#C#DictionarywithexamplesC#|MethodOverridingDifferentwaystosortanarrayindescendingorderinC#C#|IsNullOrWhiteSpace()MethodDifferencebetweenRefandOutkeywordsinC#C#|ArraysofStringsViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: ExpertLastUpdated: 19Nov,2019Anarrayisacollectionofthesametypevariable.WhereasastringisasequenceofUnicodecharactersorarrayofcharacters.Thereforearraysofstringsisanarrayofarraysofcharacters.Here,stringarrayandarraysofstringsbotharesameterm.ForExample,ifyouwanttostorethenameofstudentsofaclassthenyoucanusethearraysofstrings.Arraysofstringscanbeonedimensionalormultidimensional.Declaringthestringarray:TherearetwowaystodeclarethearraysofstringsasfollowsDeclarationwithoutsize:Syntax:String[]variable_name;orstring[]variable_name;Declarationwithsize:Syntax:String[]variable_name=newString[provide_size_here];orstring[]variable_name=newstring[provide_size_here];Example://declarationusingstringkeywordstring[]s1;//declarationusingStringclassobject//bygivingitssize4String[]s2=newString[4];InitializationofArraysofStrings:Arrayscanbeinitializedafterthedeclaration.Itisnotnecessarytodeclareandinitializeatthesametimeusingthenewkeyword.However,InitializinganArrayafterthedeclaration,itmustbeinitializedwiththenewkeyword.Itcan’tbeinitializedbyonlyassigningvalues.Example://Declarationofthearraystring[]str1,str2;//Initializationofarraystr1=newstring[5]{“Element1”,“Element2”,“Element3”,“Element4”,“Element5”};str2=newstring[]{“Element1”,“Element2”,“Element3”,“Element4”,“Element5”};Note:InitializationwithoutgivingsizeisnotvalidinC#.Itwillgivecompiletimeerror.Example:WrongDeclarationforinitializinganarray//compile-timeerror:mustgivesizeofanarrayString[]str=newString[];//error:wronginitializationofanarraystring[]str1;str1={“Element1”,“Element2”,“Element3”,“Element4”};AccessingArraysofStringsElements:Atthetimeofinitialization,wecanassignthevalue.But,wecanalsoassignthevalueofarrayusingitsindexrandomlyafterthedeclarationandinitialization.Wecanaccessanarrayvaluethroughindexing,placedindexoftheelementwithinsquarebracketswiththearrayname.Example: //declares&initializesstringarray String[]s1=newString[2]; //assignthevalue"Geeks"inarrayonitsindex0 s1[0]=10; //assignthevalue"GFG"inarrayonitsindex1 s1[1]=30; //assignthevalue"Noida"inarrayonitsindex2 s1[2]=20; //Accessingarrayelementsusingindex s1[0];//returnsGeeks s1[2];//returnsNoida Declarationandinitializationofstringarrayinasingleline:Stringarraycanalsobedeclaredandinitializedinasingleline.Thismethodismorerecommendedasitreducesthelineofcode.Example: String[]weekDays=newstring[3]{"Sun","Mon","Tue","Wed"}; Code#1:Stringarraydeclaration,initializationandaccessingitselements//C#programtoillustratetheStringarray //declaration,initializationandaccessing //itselementsusingSystem; classGeeks{ //MainMethod publicstaticvoidMain() { //Step1:ArrayDeclaration string[]stringarr; //Step2:ArrayInitialization stringarr=newstring[3]{"Element1","Element2","Element3"}; //Step3:AccessingArrayElements Console.WriteLine(stringarr[0]); Console.WriteLine(stringarr[1]); Console.WriteLine(stringarr[2]); }}Output: Element1 Element2 Element3 Code#2:Arraydeclarationandinitializationinsingleline//C#codetoillustrateArraydeclaration//andinitializationinsinglelineusingSystem; classGeeks{ //MainMethod publicstaticvoidMain() { //arrayinitializationanddeclaration String[]stringarr=newString[]{"Geeks","GFG","Noida"}; //accessingarrayelements Console.WriteLine(stringarr[0]); Console.WriteLine(stringarr[1]); Console.WriteLine(stringarr[2]); }}Output: Geeks GFG Noida Note:Inthepublicstaticvoidmain(String[]args),String[]argsisalsoanarrayofstring.Example:ToshowString[]argsisanarrayofstring.//C#programtogetthetypeof"args"usingSystem; classGFG{ //MainMethod staticpublicvoidMain(String[]args){ //usingGetType()methodto //gettypeatruntime Console.WriteLine(args.GetType()); }}Output: System.String[] C#stringarrayisbasicallyanarrayofobjects.Itdoesn’tmatterwhetheryouarecreatinganarrayofstringusingstringkeywordorStringclassobject.Botharesame.Example://C#programtogetthetypeofarraysof //stringswhicharedeclaredusing'string'//keywordand'Stringclassobject'usingSystem; classGFG{ //MainMethod staticpublicvoidMain(String[]args){ //declaringarrayofstring //usingstringkeyword string[]s1={"GFG","Noida"}; //declaringarrayofstring //usingStringclassobject String[]s2=newString[2]{"Geeks","C#"}; //usingGetType()methodto //gettypeatruntime Console.WriteLine(s1.GetType()); Console.WriteLine(s2.GetType()); }}Output: System.String[] System.String[] MyPersonalNotes arrow_drop_upSave LikePreviousString.Split()MethodinC#withExamplesNext C#|ArraysRecommendedArticlesPage:08,Jun1824,Sep1822,Nov1830,Nov1803,Dec1828,Oct2123,Oct1818,Jul1811,Oct1811,Oct1823,Dec1926,Nov21ArticleContributedBy:AYUSDAS@AYUSDASVotefordifficultyCurrentdifficulty: ExpertEasy Normal Medium Hard ExpertImprovedBy:shubham_singhArticleTags:CSharp-ArraysCSharp-stringPickedC#ReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinC#Introductionto.NETFrameworkC#|DelegatesC#|ConstructorsExtensionMethodinC#C#|ClassandObjectMorerelatedarticlesinC#C#|DataTypesC#|EncapsulationCommonLanguageRuntime(CLR)inC#C#|AbstractClassesDifferencesBetween.NETCoreand.NETFrameworkImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register
延伸文章資訊
- 1C# Array - 程式語言教學
A=new string [3];. A[0] = "dd";. A[1] = "ff";. A[2] = "gg";. ※ 註:在宣告陣列長度為N時,會自動指派N個元素給陣列。若該陣列的資料型...
- 2C# | Arrays of Strings - GeeksforGeeks
C# | Arrays of Strings ... declares & initializes string array String[] s1 = new String[2]; // as...
- 3C# Array Examples, String Arrays - Dot Net Perls
Create and loop over a string array. Access array Length and get elements at indexes.
- 4C# Arrays - W3Schools
Create an Array ... Arrays are used to store multiple values in a single variable, instead of dec...
- 5Day17-C#陣列Array、不規則陣列。神啊 - iT 邦幫忙
C#陣列簡介. 1.陣列Array是多個相同資料型別的變數,在記憶體中連續串在一起的物件,需用new進行建立物件及宣告 2.宣告時由於是要跟電腦要一串連續的記憶體空間,陣列 ...