一、String类的介绍
String类的属性
C#中自带了一些属性,如字符串的长度,在一个类中,包含有方法和属性,方法用来执行动作,属性用来保存数据 属性是一个封装结构 对外开放
Chars 在当前的String对象中获取Char对象的指定位置
Length 在当前的String对象中获取字符数
创建String类对象 下面是测试代码
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test_10_1 : MonoBehaviour
{
void Start()
{
//字符串,字符串连接
string fname, lname;
fname = "张";
lname = "三";
string fullname = fname + lname;
Debug.Log("名字: "+ fullname);
//通过使用 string 构造函数
char[] letters = { 'H', 'e', 'l', 'l', 'o' };
string greetings = new string(letters);
Debug.Log("使用string构造函数: " + greetings);
//方法返回字符串
string[] sarray = { "h", "e", "l", "l", "o" };
string message = string.Join("", sarray);
Debug.Log("使用Join方法: "+ message);
//用于转化值的格式化方法
DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);
string chat = string.Format("当前时间: {0:t} on {0:D}", waiting);
Debug.Log("使用Format方法: " + chat);
}
}
二、字符串的常用操作
1:比较字符串
比较字符串是指按照字典排序规则,判定两个字符的相对大小,按照字典规则,在一本英文字典中,出现在前面的单词小于出现在后面的单词
测试代码如下
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test_10_2 : MonoBehaviour
{
void Start()
{
string str1 = "Hello";
string str2 = "hello";
//Equals方法比较str1和str2
Debug.Log("Equals方法:"+str1.Equals(str2));
Debug.Log("Equals方法(另一种写法):" + string.Equals(str1, str2));
//Compare方法比较str1和str2
Debug.Log("Compare方法(不区分大小写):" + string.Compare(str1, str2));
Debug