using System;
using System.Linq;
using System.Text.RegularExpressions;
class B
{
public static void Main()
{
string val = "The text is using for test!";
int maxWordLength = MaxWordLength(val);
Console.WriteLine("{0} 中最长单词的长度为:{1}", val, maxWordLength);
}
public static int MaxWordLength(string val)
{
int len = 0;
string str = val;
Regex reg = new Regex(@"\w+\b");//正则表达式匹配单词
MatchCollection mc = reg.Matches(str);
//遍历每个单词,并和已知的最大长度进行比较
foreach (Match match in mc)
{
if (match.Value.Length > len)
len = match.Value.Length;
}
return len;
}
}
using System.Linq;
using System.Text.RegularExpressions;
class B
{
public static void Main()
{
string val = "The text is using for test!";
int maxWordLength = MaxWordLength(val);
Console.WriteLine("{0} 中最长单词的长度为:{1}", val, maxWordLength);
}
public static int MaxWordLength(string val)
{
int len = 0;
string str = val;
Regex reg = new Regex(@"\w+\b");//正则表达式匹配单词
MatchCollection mc = reg.Matches(str);
//遍历每个单词,并和已知的最大长度进行比较
foreach (Match match in mc)
{
if (match.Value.Length > len)
len = match.Value.Length;
}
return len;
}
}
运行程序,输出:
The text is using for test! 中最长单词的长度为:5
浙公网安备 33010602011771号