unity 字符串切割
时间: 2023-12-17 21:27:06 浏览: 27
以下是在Unity中切割字符串的示例代码:
```csharp
string var_str = "hello_world";
string[] split_str = var_str.Split('_');
for (int i = 0; i < split_str.Length; i++)
{
Debug.Log(split_str[i]); // 输出:hello 和 world
}
```
在上述代码中,我们首先定义了一个字符串`var_str`,然后使用`Split()`方法将其按照下划线进行切割,并将结果存储在一个字符串数组`split_str`中。最后,我们使用`for`循环遍历该数组,并使用`Debug.Log()`方法输出每个切割后的子字符串。
相关问题
unity字符串分割
在Unity中,你可以使用Split()方法来分割字符串。Split()方法接受一个字符数组作为参数,根据该字符数组中的字符将字符串分割成多个子字符串。以下是一个示例:
```csharp
string str = "Hello, World!";
string[] words = str.Split(' ');
foreach (string word in words)
{
Debug.Log(word);
}
```
上述示例中,我们使用空格字符作为分割符将字符串"Hello, World!"分割成两个子字符串"Hello,"和"World!",然后使用foreach循环遍历输出每个子字符串。
你可以根据自己的需求选择不同的分割符进行字符串分割。
unity 字符串操作
在 Unity 中,你可以使用 C# 的字符串操作来处理字符串。下面是一些常见的字符串操作示例:
1. 连接字符串:
```csharp
string str1 = "Hello";
string str2 = "World";
string result = string.Concat(str1, " ", str2); // 输出:Hello World
```
2. 切割字符串:
```csharp
string text = "apple,banana,orange";
string[] fruits = text.Split(','); // 将文本按逗号切割成字符串数组
foreach (string fruit in fruits)
{
Debug.Log(fruit);
}
```
3. 替换字符串:
```csharp
string text = "I love cats!";
string replacedText = text.Replace("cats", "dogs"); // 将字符串中的 "cats" 替换为 "dogs"
Debug.Log(replacedText); // 输出:I love dogs!
```
4. 检查字符串是否包含子串:
```csharp
string text = "Hello World";
bool containsHello = text.Contains("Hello"); // 检查字符串中是否包含子串 "Hello"
if (containsHello)
{
Debug.Log("Text contains 'Hello'");
}
```
这只是一些基本的例子,C# 中还有许多其他字符串操作方法,你可以根据具体需求进行查阅和使用。