大家好,我是unity3d工程师☆心疼你的一切☆,不定时更新Unity开发技巧,觉得有用记得一键三连哦。
string的比较有很多方法 Equals . Compare .Contains. Indexof . Startswith
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));
}
}
例子如下:
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));
}
}
代码如下(示例):
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));
}
}
代码如下:示例
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));
}
}
代码示例如下:
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));
}
}
StartsWith是检测字符串是否以指定的字符串开头,是就是true,否则反之 EndsWith是检测字符串是否以指定的字符串结尾,是就是true,否则反之
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));
}
}
补充:
示例:
string a = "Hello";
string b = "hello";
bool isEqual = (a == b); // false(区分大小写)示例:
bool isEqual1 = string.Equals(a, b, StringComparison.Ordinal); // 严格比较(区分大小写)
bool isEqual2 = a.Equals(b, StringComparison.OrdinalIgnoreCase); // 不区分大小写示例:
int result = string.Compare(a, b, StringComparison.CurrentCulture); // 文化敏感比较总结
本篇文章讲解了几种常用的比较字符串的方法 比较字符串是否完全一样,可以用Equals。 比较两个字符串是否一样,可以用Compare,跟Equals不同的是,Equals是返回bool类型,Compare返回int类型。 比较字符串中是否存在某个字符串可以用Contains。 比较字符串中是否存在某个字符串开头或者结尾可以用StartsWith和EndWith,也就是比Contains增加了一层限制。 比较字符串在某个字符串中出现第一次或者最后一次的下标,可以用IndexOf和LastIndexOf
本次就是这么多了,点关注不迷路哦