zoukankan      html  css  js  c++  java
  • C#中得字符串、集合等的几个小练习

    1,/*接受一串英文,将里面的单词反序输出   例:I Love You → I evoL uoY*/

    1 string a = Console.ReadLine();
    2             string[] b = a.Split(' ');
    3             for (int i = 0; i < b.Length; i++)
    4             {
    5 
    6                 Console.Write(TurnString(b[i]) + " ");
    7             }
    1         public static  String TurnString(string s)
    2         {
    3             StringBuilder sb = new StringBuilder();
    4             for (int i = s.Length-1; i>=0; i--)
    5             {
    6                 sb.Append(s[i]);
    7             }
    8             return sb.ToString();
    9         }

    2,/*”2012年12月21日”从日期字符串中把年月日分别取出来,打印到控制台*/

                string a = "2013年5月26日";
                String[] b = a.Split('年', '月', '日');
                foreach (var item in b)
                {
                    Console.WriteLine(item);
                }
    

      3,stringBuilder

    在进行大量字符串拼接的时候一般都用StringBuilder,字符串本身的不可变性,每次拼接的时候都会创建 一个String对象,这个过程本身就耗费资源,因为它不会创造多余的垃圾内存,拼接的时候它只是在一块内存上进行操作。所以说在进行大量字符串拼接的时候就不要用+了,最好StringBuilder一下,免得开辟太多的内存空间

    4,集合  (命名空间:System.Collections;)

    首先要说的就是ArrayList,它其实就是一个object数组,什么都可以存,不过一般情况下我都会去用list集合,因为它可以指明类型,就像定义变量我绝对不会去把int定义成object,并且用起来也方便

    5,数据字典  (必须要包括命名空间:System.Collections;)

    Dictionary里面的元素必须是键值对,键要是唯一的,而值可以不是,并且键和值得类型可以不是一样的,通过键值对查询时非常快的,就像查字典一样

     1  Dictionary<string, string> d = new Dictionary<string, string>();
     2             d.Add("姓名","小明");
     3             d.Add("年龄","18");
     4             d.Add("性别", "");
     5             foreach (var key in d.Keys)  //遍历键
     6             {
     7                 Console.WriteLine("键:{0}",key);
     8             }
     9             foreach (var value in d.Values)  //遍历值
    10             {
    11                 Console.WriteLine("值:{0}",value);
    12             }
    13             Console.WriteLine(d["姓名"]);//直接拿值
    14 
    15             foreach (KeyValuePair<String,String> dictionary in d)  //遍历字典
    16             {
    17                 Console.WriteLine("键:{0},值:{1}",dictionary.Key,dictionary.Value);
    18             }
  • 相关阅读:
    237. Delete Node in a Linked List
    430. Flatten a Multilevel Doubly Linked List
    707. Design Linked List
    83. Remove Duplicates from Sorted List
    160. Intersection of Two Linked Lists
    426. Convert Binary Search Tree to Sorted Doubly Linked List
    142. Linked List Cycle II
    类之间的关系
    初始化块
    明确类和对象
  • 原文地址:https://www.cnblogs.com/tuibian/p/3633769.html
Copyright © 2011-2022 走看看