C# string字符串介绍

好久没登录写写博客了

翻翻以前的博客,发现有了deepseek,很多代码都变得那么不值一提。

也就当个备忘录吧。

运行环境 visual studio 2022 + 4.6.1版本

能够编译通过,运行起来的代码

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;


namespace MachineDemo.learn
{
    public class Stringlearn
    {
        public void mystring()
        {
            // 声明一个字符串变量
            string greeting;

            // 直接声明并初始化
            //string message = "Hello, C# and C++ and C !";

            string firstName = "John";
            string lastName = "Doe";
            string fullName = firstName + " " + lastName; // "John Doe"

            int age = 30;
            string message = "My name is {firstName} {lastName} and I am {age} years old.";

            string emptyString = string.Empty; // 推荐使用,效率更高
            string anotherEmptyString = ""; // 同样有效


            char[] charArray = { 'H', 'e', 'l', 'l', 'o' };
            string hello = new string(charArray); // "Hello"

            string stars = new string('*', 5); // ""

            string test = new string(new[] { 'a', 'b', 'c' }); // "abc"

            string str = "Hello";
            char[] chars = str.ToCharArray(); // ['H', 'e', 'l', 'l', 'o']


            string str1 = "Hello World";
            string upper = str1.ToUpper(); // "HELLO WORLD"
            string lower = str1.ToLower(); // "hello world"

            string a = "Hello";
            string b = "World";
            string result = string.Concat(a, " ", b); // "Hello 

            string[] colors = { "Red", "Green", "Blue" };
            string joinedColors = string.Join(", ", colors); // 


            string sentence = "Hello,World,Today";
            string[] parts = sentence.Split(','); // ["Hello", "World", "Today"]

            string str2 = "Hello World";
            string replaced = str2.Replace("World", "C"); // "Hello C"

            string str3 = "Hello,World";
            string sub = str3.Substring(0, 5); // "Hello"


            string str4 = "Hello,World";
            int index = str4.IndexOf('o'); // 4
            int lastIndex = str4.LastIndexOf('o'); // 7


            string str5 = "Hello,World";
            bool contains = str5.Contains("World"); // true

            string str6 = "Hello,World";
            string removed = str6.Remove(5, 1); // "HelloWorld"

            string str7 = "   Hello, World!   ";
            string trimmed = str7.Trim(); // "Hello, World!"

            string str8 = "Hello,World!123";
            // 替换所有数字
            string replaced1 = Regex.Replace(str8, @"\d", "*"); // "Hello,World!"
                                                            // 拆分字符串
            string[] words = Regex.Split(str8, @"[,!]");
            // words = ["Hello", "World", "123"]

            StringBuilder sb = new StringBuilder();
            sb.Append("Hello");
            sb.Append(" World");
            sb.Replace("World", "C");
            string result2 = sb.ToString(); // "Hello C"
        }
    }
}

下面是代码deepseek讲解

csharp 复制代码
好的!以下是关于C中string类型的详细讲解,包括基本使用方法、高级玩法以及代码示例。

 一、string类型概述
string是C中最常用的数据类型之一,用于表示字符串。字符串是字符的有序集合,可以包含字母、数字、符号等。

 1. 声明和初始化字符串
csharp
// 声明一个字符串变量
string greeting;

// 初始化字符串
greeting = "Hello, World!";

// 直接声明并初始化
string message = "Hello, C!";

 二、字符串拼接
字符串拼接是将多个字符串组合成一个字符串的操作。

 1. 使用 + 运算符
csharp
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName; // "John Doe"

 2. 使用字符串插值(推荐)
csharp
int age = 30;
string message = "My name is {firstName} {lastName} and I am {age} years old.";
// 输出:My name is John Doe and I am 30 years old.

 三、通过string构造函数创建字符串
string类型提供了多种构造函数来创建字符串。

 1. 使用空字符串
csharp
string emptyString = string.Empty; // 推荐使用,效率更高
string anotherEmptyString = ""; // 同样有效

 2. 使用字符数组
csharp
char[] charArray = { 'H', 'e', 'l', 'l', 'o' };
string hello = new string(charArray); // "Hello"

 3. 使用字符和重复次数
csharp
string stars = new string('*', 5); // "*****"

 4. 使用初始化器
csharp
string test = new string(new[] { 'a', 'b', 'c' }); // "abc"

 四、常用字符串方法
C提供了许多内置方法来操作字符串。

 1. ToCharArray():将字符串转换为字符数组
csharp
string str = "Hello";
char[] chars = str.ToCharArray(); // ['H', 'e', 'l', 'l', 'o']

 2. ToUpper() 和 ToLower():切换大小写
csharp
string str = "Hello World";
string upper = str.ToUpper(); // "HELLO WORLD"
string lower = str.ToLower(); // "hello world"

 3. Concat():拼接字符串
csharp
string a = "Hello";
string b = "World";
string result = string.Concat(a, " ", b); // "Hello World"

 4. Join():将数组或集合拼接成字符串
csharp
string[] colors = { "Red", "Green", "Blue" };
string joinedColors = string.Join(", ", colors); // "Red, Green, Blue"

 5. Split():分割字符串
csharp
string sentence = "Hello,World,Today";
string[] parts = sentence.Split(','); // ["Hello", "World", "Today"]

 6. Replace():替换子字符串
csharp
string str = "Hello World";
string replaced = str.Replace("World", "C"); // "Hello C"

 7. Substring():获取子字符串
csharp
string str = "Hello,World";
string sub = str.Substring(0, 5); // "Hello"

 8. IndexOf() 和 LastIndexOf():查找字符或子字符串的位置
csharp
string str = "Hello,World";
int index = str.IndexOf('o'); // 4
int lastIndex = str.LastIndexOf('o'); // 7

 9. Contains():检查字符串是否包含某个子字符串
csharp
string str = "Hello,World";
bool contains = str.Contains("World"); // true

 10. Remove():移除子字符串
csharp
string str = "Hello,World";
string removed = str.Remove(5, 1); // "HelloWorld"

 11. Trim():去除首尾空格
csharp
string str = "   Hello, World!   ";
string trimmed = str.Trim(); // "Hello, World!"

 五、高级玩法
 1. 正则表达式
System.Text.RegularExpressions命名空间提供了强大的字符串处理功能。
csharp
using System.Text.RegularExpressions;

string str = "Hello,World!123";
// 替换所有数字
string replaced = Regex.Replace(str, @"d", ""); // "Hello,World!"
// 拆分字符串
string[] words = Regex.Split(str, @"[,!]");
// words = ["Hello", "World", "123"]

 2. StringBuilder(性能优化)
当需要频繁修改字符串时,StringBuilder比直接操作string更高效。
csharp
using System.Text;

StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append(" World");
sb.Replace("World", "C");
string result = sb.ToString(); // "Hello C"

 六、完整示例
csharp
using System;
using System.Text;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        // 基础操作
        string greeting = "Hello, World!";
        Console.WriteLine(greeting);

        // 字符串拼接
        string firstName = "John";
        string lastName = "Doe";
        string fullName = "{firstName} {lastName}";
        Console.WriteLine(fullName);

        // 字符串方法
        string str = "Hello,World!";
        string[] parts = str.Split(',');
        foreach (string part in parts)
        {
            Console.WriteLine(part);
        }

        // 正则表达式
        string replaced = Regex.Replace(str, @",", " ");
        Console.WriteLine(replaced); // "Hello World!"

        // StringBuilder
        StringBuilder sb = new StringBuilder();
        sb.Append("Hello");
        sb.Append(" World");
        sb.Replace("World", "C");
        Console.WriteLine(sb.ToString()); // "Hello C"
    }
}

 七、总结
 string是C中最常用的数据类型,用于表示字符串。
 常用操作包括拼接、拆分、替换、大小写转换等。
 对于复杂操作,可以使用正则表达式或StringBuilder来提高效率。

希望这些内容对你有所帮助!如果有任何问题,欢迎随时提问!
相关推荐
nqqcat~9 分钟前
STL常用算法
开发语言·c++·算法
Matlab光学33 分钟前
MATLAB仿真:Ince-Gaussian光束和Ince-Gaussian矢量光束
开发语言·算法·matlab
珹洺1 小时前
Java-servlet(十)使用过滤器,请求调度程序和Servlet线程(附带图谱表格更好对比理解)
java·开发语言·前端·hive·hadoop·servlet·html
勘察加熊人1 小时前
c#使用forms实现helloworld和login登录
开发语言·c#
双叶8361 小时前
(C语言)学生信息表(学生管理系统)(基于通讯录改版)(正式版)(C语言项目)
c语言·开发语言·c++·算法·microsoft
IT从业者张某某2 小时前
Python数据可视化-第4章-图表样式的美化
开发语言·python·信息可视化
脑子慢且灵2 小时前
【蓝桥杯】 枚举和模拟练习题
java·开发语言·职场和发展·蓝桥杯·模拟·枚举
我不是程序猿儿2 小时前
【C#】设备回帧太快、数据没收完整就被读取,导致帧被拆、混、丢,很常见,尤其在高频通信设备,解决方案
开发语言·c#
小郝 小郝2 小时前
(C语言)指针运算 习题练习1.2(压轴难题)
java·开发语言·算法