C#字符串梳理及练习

一、字符串API梳理:

字符串:字符串不可以被修改 , 一般调用字符串API的时候使用新的变量来接收

using System;
using System.Linq;

namespace _10.梳理字符串API
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 1。
            string str = "hello";
            // 字符串串联(合并) string.Concat() || string.Join()
            char[] chars = str.Concat(new char[] { ' ', 'w', 'o', 'r', 'l', 'd' }).ToArray();
            Console.WriteLine(chars);

            string result1 = string.Concat(str, " ", "world", " how are you");
            Console.WriteLine(result1);

            // 判断字符串以xx开头,以xx结尾
            Console.WriteLine(str.StartsWith("He", StringComparison.OrdinalIgnoreCase));
            Console.WriteLine(str.EndsWith("llo", StringComparison.OrdinalIgnoreCase));

            // 判断字符串相等
            string str2 = "hello";
            //if ("abc" == "abc")
            //if (str == str2)
            if (str.Equals(str2))
            {
                Console.WriteLine("成立");
            }

            Class1 cls1 = new Class1();
            Class1 cls2 = new Class1();
            //if (cls1 != cls2)
            if (!cls1.Equals(cls2))
            {
                Console.WriteLine("不成立");
            }
            Console.WriteLine(object.ReferenceEquals(cls1, cls2));

            Console.WriteLine("-----------");

            // 格式化:string.Format()

            // 查索引:IndexOf(),LastIndexOf()

            // 插入  e索引是1
            Console.WriteLine(str.Insert(2, "AAA")); // HeAAAllo

            // 判断空  string.IsNullOrEmpty() string.IsNullOrWhiteSpace()

            // 不足宽度补字符  str.PadLeft(), str.PadRight()
            Console.WriteLine(str.PadLeft(10));
            Console.WriteLine(str.PadLeft(10, 'A'));
            Console.WriteLine(str.PadRight(10));
            Console.WriteLine(str.PadRight(10, 'A'));
            // 删除
            Console.WriteLine(str.Remove(1, 2));
            // 替换
            Console.WriteLine(str.Replace('l', 'L'));
            Console.WriteLine(str.Replace("ll", "L"));
            // 自动扩容
            // 截取
            Console.WriteLine(str.Substring(0, 2));
            // 去除空白  str.Trim(),str.TrimLeft(),str.TrimRigth()
            // 拆分 str.Split()
            // 转换大小写 str.ToUpper(), str.ToLower()
            // 转换成字符数组 str.ToCharArray()

            // 2。hello
            char[] chars2 = new char[5];
            str.CopyTo(1, chars2, 1, 4);
            Console.WriteLine(str);
            Console.WriteLine(chars2);

            if (str.CompareTo("hello") == 0)
            {
                Console.WriteLine("成立1");
            }

            if ("a".CompareTo("b") < 0)
            {
                Console.WriteLine("成立2");
            }

            if ("b".CompareTo("a") > 0)
            {
                Console.WriteLine("成立3");
            }
            /*if("HELLO" == "hello")
            {
                Console.WriteLine("成立4");
            }*/

            if (string.Compare("A", "a", true) == 0)
            {
                Console.WriteLine("成立4");
            }

            string result2 = string.Copy(str);
            Console.WriteLine(result2);

            Console.WriteLine(string.ReferenceEquals(result2, str));
            Console.WriteLine(string.ReferenceEquals("hello", "hello"));

            string str3 = "world";
            string str4 = string.Intern(str3);
            Console.WriteLine(string.ReferenceEquals(str3,str4));
        }
    }
}

 二、字符串练习:

1:字符串反序输出,如:hello ===> olleh

string str = "hello";
char[] array = str.ToCharArray();
Array.Reverse(array);
string arr = new string(array);
Console.WriteLine("原来字符串是:" + str);
Console.WriteLine("字符串反向输出是:" + arr);

2:将“hello you world”反向输出“world you hello”

string str1 = "hello you world";
string[] str2 = str1.Split(' ');
Array.Reverse(str2);
string str3 = String.Join(" ", str2);
Console.WriteLine(str3);

3:Email中提取用户名和域名,如:ddy_dhj@163.com    用户名:ddy_dhj 域名:www.163.com

string str4 = "ddy_dhj@163.com";
string[] str5 = str4.Split('@');
if (str5.Length == 2)
{
    string a = str5[0];
    string b = str5[1];
    Console.WriteLine("用户名是:"+a);
    Console.WriteLine("域名是:" + b);
}
else
{
    Console.WriteLine("你输入的格式有问题");
}

4:字符串某个子串所在位置,如:hello,查ll在字符串中的位置。多种方式实现。提示:for, indexof

string str6 = "hello";
string str7 = "ll";
int num = str6.IndexOf(str7);
Console.WriteLine(num);

 5:用户输入的字符串中有多少大写字母、小写字母、数字、其他字符的个数。如:hello,  h: 1,e: 1,l: 2,o: 1

    Start:
    Console.Write("请输入字符串:");
    string input = Console.ReadLine();
    if (string.IsNullOrWhiteSpace(input))
    {
        Console.WriteLine("字符串不能为空或空白!请输入");
        goto Start;
    }
    Dictionary<char, int> charCount = GetCharCount(input);
    foreach (KeyValuePair<char, int> kvp in charCount)
    {
        Console.WriteLine($"{kvp.Key}:{kvp.Value}");
    }
    Console.ReadKey();
static Dictionary<char, int> GetCharCount(string s)
{
    Dictionary<char, int> dict = new Dictionary<char, int>();
    foreach (char c in s)
    {
        if (!char.IsWhiteSpace(c))  // char.IsWhiteSpace(c)判断字符是否是空格
        {
            // dict.ContainsKey(c)判断字典中是否包含某个key
            if (dict.ContainsKey(c))   //  dict[c]类似于strs[i]
                dict[c]++;
            else
                dict.Add(c, 1);
        }
    }
    return dict;
}

6:用户输入的字符串中有多少大写字母、小写字母、数字、其他字符的个数。

static void Main(string[] args)
{
    Start:
    Console.WriteLine("请输入一个字符串:");
    string input = Console.ReadLine();
    if (string.IsNullOrWhiteSpace(input))
    {
        Console.WriteLine("字符串不能为空或空白!请输入");
        goto Start;
    }

    // 连续定义多个变量
    int upperCase, lowerCase, digit, other;
    upperCase = lowerCase = digit = other = 0;

    foreach (char c in input)
    {
        if (char.IsUpper(c))
        {
            upperCase++;
        }
        else if (char.IsLower(c))
        {
            lowerCase++;
        }
        else if (char.IsDigit(c))
        {
            digit++;
        }
        else
        {
            other++;
        }
    }
    Console.WriteLine("大写字母数量:" + upperCase);
    Console.WriteLine("小写字母数量:" + lowerCase);
    Console.WriteLine("数字数量:" + digit);
    Console.WriteLine("其他字符数量:" + other);
}

7:让用户输入一句话判断有没有邪恶两个字,有的话用**替换。如:老赵是个邪恶的人==》老赵是个**的人

// aaa邪恶bbb====[aaa,bbb]====[aaa,邪恶,bbb]
// aaa邪恶bbb邪恶ccc====[aaa,bbb,ccc]====[aaa,邪恶,bbb,邪恶,ccc]
// aaa邪恶bbb邪恶ccc邪恶ddd====[aaa,bbb,ccc,ddd]====[aaa,邪恶,bbb,邪恶,ccc,邪恶,ddd]

// 1。 把输入的字符串拆分成字符串数组
string[] strs = input.Split(new string[] { "邪恶" }, StringSplitOptions.None);
// 2。准备数组
string[] newStrs = new string[2 * strs.Length - 1] ;
for (int i = 0; i < newStrs.Length; i = i + 2)
{
    newStrs[i] = strs[i / 2]; // strs[0,1,2,3]  i=0 i=2 i=4 i=6
    if (i < newStrs.Length - 1)
        newStrs[i + 1] = "邪恶";
}
// 3。循环数组
for (int j = 0; j < newStrs.Length; j++)
{
    Console.ForegroundColor = newStrs[j] == "邪恶" ? ConsoleColor.Red : ConsoleColor.White;
    Console.Write(newStrs[j]);
}

 8:把字符串数组转换成|连接的字符串。  5个

// 用来存储用户输入的字符串
string[] strings = new string[] { };

Start:
Console.Write("请输入字符串:");
string input = Console.ReadLine();
if (string.IsNullOrEmpty(input.Trim()))
{
    goto Start;
}
strings = strings.Append(input).ToArray() ;
if (strings.Length < 5)
{
    goto Start;
}
Console.WriteLine(string.Join("|", strings)); 

9:输入一个网址,判断顶级域名是什么类型,com为商业网站,net为网络服务机构网站,org为非营利组织网站,gov为政府网站,edu为教育网站;如:用户输入https://www.baidu.com,提示:顶级域名为:.com,这是一个商业网站

Start:
Console.Write("输入一个网址:");
string url = Console.ReadLine();
// 正则表达式校验合法性
Regex reg = new Regex("^https://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?$");
if (!reg.IsMatch(url))
{
    goto Start;
}
string[] strs = url.Split('.');
string lastStr = strs[strs.Length - 1];
switch (lastStr)
{
    case "com":
        Console.WriteLine("商业网站");
        break;
    case "org":
        Console.WriteLine("非营利组织网站");
        break;
    case "gov":
        Console.WriteLine("政府网站");
        break;
    default:
        Console.WriteLine("未知");
        break;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值