cshap判断字符中是是否存在字母并去除
时间: 2023-12-18 16:03:29 浏览: 23
非字母字符,该怎么做?
可以使用正则表达式来判断字符串中是否存在字母,并去除非字母字符。具体代码如下:
string input = "Hello, World! 123";
string output = Regex.Replace(input, "[^a-zA-Z]", "");
Console.WriteLine(output);
输出结果为:HelloWorld
相关问题
cshap 读取TXT文件 判断包含ST字符后的第三行文字是否包含字母I
以下是C#代码示例,用于读取TXT文件并判断包含ST字符后的第三行文字是否包含字母I:
```csharp
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string filePath = "example.txt";
bool containsI = false;
try
{
using (StreamReader sr = new StreamReader(filePath))
{
string line;
bool foundST = false;
int lineCount = 0;
while ((line = sr.ReadLine()) != null)
{
lineCount++;
if (line.Contains("ST"))
{
foundST = true;
}
else if (foundST && lineCount == 3)
{
if (line.Contains("I"))
{
containsI = true;
}
break;
}
}
}
if (containsI)
{
Console.WriteLine("The third line after 'ST' contains the letter 'I'.");
}
else
{
Console.WriteLine("The third line after 'ST' does not contain the letter 'I'.");
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
Console.ReadLine();
}
}
```
在上面的代码中,我们首先定义了要读取的文件路径和一个布尔变量“containsI”,用于记录第三行是否包含字母“I”。然后,我们使用StreamReader打开文件,并使用ReadLine方法逐行读取文件内容。
在每一行中,我们检查该行是否包含“ST”字符,如果是,则将布尔变量“foundST”设置为true。一旦找到了“ST”,我们就开始计数,以便确定第三行。当计数到第三行时,我们检查该行是否包含字母“I”。如果是,则将布尔变量“containsI”设置为true,并立即退出while循环。
最后,我们检查“containsI”的值并输出相应的消息。请注意,我们还捕获了任何异常,并在控制台中输出错误消息。
CShap 字符串中删除重复的字符 源代码
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();
}