C# 去除string[]逗号
时间: 2023-09-09 14:11:31 浏览: 53
如果你想将一个 string[] 数组中的所有字符串中的逗号去除,你可以使用以下代码:
```csharp
string[] arr = { "hello, world", "how, are, you" };
for (int i = 0; i < arr.Length; i++)
{
arr[i] = arr[i].Replace(",", "");
}
```
这个代码会遍历数组中的所有字符串,将其中的逗号替换为空字符串。最终,`arr` 数组中的元素将会变成:
```
{ "hello world", "how are you" }
```
相关问题
C# 去除string[]逗号转为string
如果你希望将一个 string[] 数组中的所有字符串中的逗号去除,并将结果以字符串形式返回,你可以使用以下代码:
```csharp
string[] arr = { "hello, world", "how, are, you" };
string result = string.Join(" ", arr.Select(s => s.Replace(",", "")));
```
这个代码会遍历数组中的所有字符串,将其中的逗号替换为空格,然后用 `string.Join` 方法将所有字符串拼接成一个字符串,中间用空格隔开。最终,`result` 变量的值将会是:
```
"hello world how are you"
```
C#拆分string
以下是C#中拆分字符串的方法:
1.使用String.Split()函数,该函数可以将一个字符串按照指定的分隔符拆分成一个字符串数组。
```csharp
string str = "apple,banana,orange";string[] arr = str.Split(',');
foreach (string s in arr)
{
Console.WriteLine(s);
}
// 输出:
// apple
// banana
// orange
```
2.使用StringSplitOptions.RemoveEmptyEntries参数,该参数可以在拆分时自动忽略空字符串。
```csharp
string str = "apple,,banana,orange,";
string[] arr = str.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in arr)
{
Console.WriteLine(s);
}
// 输出:
// apple
// banana
// orange
```
3.使用StringSplitOptions.RemoveEmptyEntries参数和StringSplitOptions.TrimEntries参数,该参数可以在拆分时自动忽略空字符串,并去除每个字符串的前后空格。
```csharp
string str = " apple , , banana , orange , ";
string[] arr = str.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
foreach (string s in arr)
{
Console.WriteLine(s);
}
// 输出:
// apple
// banana
// orange
```