CShap 字符串中删除重复的字符 源代码
时间: 2023-12-08 20:03:32 浏览: 167
string RemoveDuplicateChars(string str)
{
//创建一个HashSet存储已经出现过的字符
HashSet<char> set = new HashSet<char>();
//创建一个StringBuilder用于构建新的字符串
StringBuilder sb = new StringBuilder();
//遍历字符串中的每个字符
foreach (char c in str)
{
//如果字符没有出现过则添加到HashSet中,并在StringBuilder中添加该字符
if (!set.Contains(c))
{
set.Add(c);
sb.Append(c);
}
}
//返回StringBuilder中构建的新字符串
return sb.ToString();
}
相关问题
CShap 字符串压缩 源代码
以下是一个C#字符串压缩的示例代码:
```csharp
public static string Compress(string uncompressed)
{
byte[] data = Encoding.UTF8.GetBytes(uncompressed);
using (MemoryStream outputStream = new MemoryStream())
{
using (DeflateStream compressionStream = new DeflateStream(outputStream, CompressionMode.Compress))
{
compressionStream.Write(data, 0, data.Length);
}
return Convert.ToBase64String(outputStream.ToArray());
}
}
public static string Decompress(string compressed)
{
byte[] data = Convert.FromBase64String(compressed);
using (MemoryStream inputStream = new MemoryStream(data))
{
using (MemoryStream outputStream = new MemoryStream())
{
using (DeflateStream decompressionStream = new DeflateStream(inputStream, CompressionMode.Decompress))
{
decompressionStream.CopyTo(outputStream);
}
return Encoding.UTF8.GetString(outputStream.ToArray());
}
}
}
```
这个示例使用了C#的标准库中的DeflateStream类来进行压缩和解压缩。压缩的过程是将字符串转换成字节数组,然后使用DeflateStream进行压缩并转换成Base64字符串。解压缩的过程是将Base64字符串转换成字节数组,然后使用DeflateStream进行解压缩并转换成字符串。
CShap 字符串是否为pallindrome排列 源代码
以下是C#程序代码,用于检查给定字符串是否为回文排列:
```
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string str = "racecar";
bool isPalindromePermutation = IsPalindromePermutation(str);
Console.WriteLine(isPalindromePermutation);
}
public static bool IsPalindromePermutation(string str)
{
Dictionary<char, int> charCount = new Dictionary<char, int>();
foreach (char c in str)
{
if (c != ' ')
{
if (charCount.ContainsKey(c))
{
charCount[c]++;
}
else
{
charCount[c] = 1;
}
}
}
int oddCount = 0;
foreach (int count in charCount.Values)
{
if (count % 2 != 0)
{
oddCount++;
}
if (oddCount > 1)
{
return false;
}
}
return true;
}
}
```
该程序使用一个字典来计算字符串中每个字符的出现次数。如果字符串是回文排列,则只能有一个或零个字符的出现次数为奇数。如果字符串不是回文排列,则有两个或更多字符的出现次数为奇数。
阅读全文