系列文章目录
unity知识点
大家好,我是unity3d工程师☆心疼你的一切☆,不定时更新Unity开发技巧,觉得有用记得一键三连哦。
前言
string的比较有很多方法 Equals . Compare .Contains. Indexof . Startswith
一、Equals
1.1 Equals和运算符==是一样的
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class String_Equals : MonoBehaviour
{
string str1 = "java";
string str2 = "c++";
string str3 = "c++";
void Start()
{
// 两种方法是等价的
Debug.Log("使用 Equals方法:" + str1.Equals(str2));
Debug.Log("使用 == 运算符:" + (str1 == str2));
Debug.Log("使用 == 运算符:" + (str3 == str2));
}
}
1.2 运行结果
二、Compare
2.1 Compare 比较如果不相等返回-1否则0
例子如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class String_Compare : MonoBehaviour
{
string str1 = "java";
string str2 = "c++";
string str3 = "c++";
void Start()
{
Debug.Log("使用 Compare方法,不相等:" + string.Compare(str1, str2));
Debug.Log("使用 Compare方法,相等:" + string.Compare(str2, str3));
}
}
2.2 结果如下图
三. Contains
3.1 Contains比较传过来的参数,有没有相等的,有就是true否则就是false
代码如下(示例):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class String_Contains : MonoBehaviour
{
string str1 = "java";
string str2 = "c++";
string str3 = "c++";
char c3 = 'c';
void Start()
{
Debug.Log("使用 Contains方法,参数char:" + str1.Contains(c3));
Debug.Log("使用 Contains方法,参数string:" + str2.Contains(c3));
}
}
3.2 效果图如下
四. Indexof
4.1 Indexof 是从前向后找,也就是按顺序,返回的字符是第一次出现的索引
代码如下:示例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class String_Indexof : MonoBehaviour
{
string str1 = "jacvac";
string str2 = "c++";
string str3 = "c++";
char c3 = 'c';
void Start()
{
Debug.Log("使用 Indexof方法,参数char:" + str1.IndexOf(c3));
//Debug.Log("使用 Contains方法,参数string:" + str2.Contains(c3));
}
}
4.2 结果图如下
五. LastIndexof
5.1 LastIndexof方法也是从前往后找,返回的字符是在字符串中最后一次出现的索引
代码示例如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class String_LastIndexof : MonoBehaviour
{
string str1 = "jacvac";
string str2 = "c+c+";
string str3 = "c++";
char c3 = 'c';
void Start()
{
Debug.Log("使用 LastIndexOf方法,参数string:" + str2.LastIndexOf(c3));
}
}
5.2 结果如下
六. StartsWith和EndsWith
StartsWith是检测字符串是否以指定的字符串开头,是就是true,否则反之
EndsWith是检测字符串是否以指定的字符串结尾,是就是true,否则反之
6.1 代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class String_StartsWith : MonoBehaviour
{
string str1 = "javac";
string str2 = "c++";
string str3 = "c";
void Start()
{
Debug.Log("使用 StartsWith方法:" + str2.StartsWith (str3));
Debug.Log("使用 EndsWith方法:" + str1.EndsWith(str3));
}
}
6.2 结果如下图
总结
本篇文章讲解了几种常用的比较字符串的方法
比较字符串是否完全一样,可以用Equals。
比较两个字符串是否一样,可以用Compare,跟Equals不同的是,Equals是返回bool类型,Compare返回int类型。
比较字符串中是否存在某个字符串可以用Contains。
比较字符串中是否存在某个字符串开头或者结尾可以用StartsWith和EndWith,也就是比Contains增加了一层限制。
比较字符串在某个字符串中出现第一次或者最后一次的下标,可以用IndexOf和LastIndexOf
本次就是这么多了,点关注不迷路哦