📌  相关文章
📜  检查字符串是否在字符串 [] c# - Lua (1)

📅  最后修改于: 2023-12-03 15:26:46.046000             🧑  作者: Mango

检查字符串是否在字符串 [] c# - Lua

在C#和Lua中,我们经常需要检查一个字符串是否包含于另一个字符串中。这个任务可以通过字符串的Contains方法来完成。

C#中的实现

在C#中,可以使用字符串的Contains方法来检查一个字符串是否包含于另一个字符串中。

以下是一个示例代码,演示如何使用Contains方法检查一个字符串是否在另一个字符串中:

string haystack = "The quick brown fox jumps over the lazy dog.";
string needle = "fox";

bool containsFox = haystack.Contains(needle);

if (containsFox)
{
    Console.WriteLine("The string '{0}' was found in the string '{1}'.", needle, haystack);
}
else
{
    Console.WriteLine("The string '{0}' was not found in the string '{1}'.", needle, haystack);
}

输出结果为:

The string 'fox' was found in the string 'The quick brown fox jumps over the lazy dog.'.

需要注意的是,Contains方法默认是区分大小写的。如果不区分大小写,可以使用StringComparison类的IgnoreCase枚举类型:

bool containsFox = haystack.Contains(needle, StringComparison.OrdinalIgnoreCase);
Lua中的实现

在Lua中,可以使用字符串的find方法来检查一个字符串是否包含于另一个字符串中。

以下是一个示例代码,演示如何使用find方法检查一个字符串是否在另一个字符串中:

local haystack = "The quick brown fox jumps over the lazy dog."
local needle = "fox"

local containsFox = haystack:find(needle)

if containsFox ~= nil then
    print("The string '" .. needle .. "' was found in the string '" .. haystack .. "'.")
else
    print("The string '" .. needle .. "' was not found in the string '" .. haystack .. "'.")
end

输出结果为:

The string 'fox' was found in the string 'The quick brown fox jumps over the lazy dog.'.

需要注意的是,Lua中的find方法是区分大小写的。如果不区分大小写,可以使用string.lower函数:

local haystack = "The quick brown fox jumps over the lazy dog."
local needle = "fOx"

local containsFox = haystack:lower():find(needle:lower())

if containsFox ~= nil then
    print("The string '" .. needle .. "' was found in the string '" .. haystack .. "'.")
else
    print("The string '" .. needle .. "' was not found in the string '" .. haystack .. "'.")
end

输出结果为:

The string 'fOx' was found in the string 'The quick brown fox jumps over the lazy dog.'.
结论

在C#和Lua中,检查字符串是否在字符串中是一个经常用到的任务。使用字符串的Contains方法和find方法可以轻松实现这个任务。需要注意大小写的问题,以便能够正确地检测字符串是否在字符串中。