我有一个名字(骑自行车者)列表,按姓氏,名字的顺序排列。我想运行代码所以它将Lastname放在Firstname前面。 Lastname始终以大写字母书写,并且可以包含一个以上的值。所以我决定将字符串拆分为数组,这是有效的。只把它放在一起很难。
这是我到目前为止的代码:(尝试使用for和foreach)
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string fullName = "BELAMONTE VALVERDE Allechandro Jesus";
string[] words = fullName.Split(' ');
foreach (string word in words)
if (word.ToUpper() == word)
{
string lastname = string.Join(" ", word);
Console.WriteLine(word);
}
Console.ReadLine();
string fullName2 = "GONZALEZ GALDEANO Igor Anton";
string[] words2 = fullName2.Split(' ');
for (int i = 0; i < words2.Length; i++)
{
string word2 = words2[i];
if (word2.ToUpper() == word2)
{
string lastname2 = string.Join(" ", word2);
Console.WriteLine(lastname2);
}
}
Console.ReadLine();
}
}
}
它提供了类似
的输出BELAMONTE VALVERDE
BELAMONTE VALVERDE
我希望它在一条线上。实际使用将从表中读取记录转换为 并将其替换为已加载的项目。
答案 0 :(得分:3)
您要做的第一件事是封装正在测试字符串的一部分是否为大写的逻辑: -
Detecting if a string is all CAPS
public bool IsAllUppercase(string value)
{
return value.All(x => x.IsUpper);
}
然后你要封装提取你名字的大写部分的逻辑
public string GetUppercasePart(string value)
{
return string.Join(" ", value.Split(" ").Where(x => IsAllUppercase(x));
}
然后获取名称的大写部分非常简单: -
var lastName = GetUppercasePart("BELAMONTE VALVERDE Allechandro Jesus");
但我得到的印象是,除了获取字符串中的所有大写单词之外,还有更多问题。
警告:如果这是您要在计算机以外的任何地方运行的生产应用程序的代码,那么您需要考虑IsUpper
表示不同的内容不同的语言环境。您可能想了解国际化问题如何影响字符串操作: -
答案 1 :(得分:0)
如果您知道姓氏将全部大写并且将在名字前面,您可以使用正则表达式来解析大写字母和名称的其余部分。
这是正则表达式:
([A-Z\s]+) (.*)
这个会匹配大写单词,其间可以有空格,即\s
([A-Z\s]+)
这个将匹配名称的其余部分
(.*)
因此,切换一个名称的最终代码可能如下所示:
static void Main(string[] args)
{
string fullName = "BELAMONTE VALVERDE Allechandro Jesus";
string pattern = @"([A-Z\s]+) (.*)";
var parsedName = Regex.Match(fullName,pattern);
string firstName = parsedName.Groups[2].ToString();
string lastName = parsedName.Groups[1].ToString();
string result = firstName + " " + lastName;
}
答案 2 :(得分:-1)
这里有代码设计问题:
foreach (string word in words)
if (word.ToUpper() == word)
{
string lastname = string.Join(" ", word);
Console.WriteLine(word);
}
你想做的就是写一次姓氏,对吧?让我们分开算法:
string[] words = fullName.Split(' ');
我们不需要“保存”这些单词,这要归功于一个名为StringBuilder的方便的类,所以它会像这样:
string fullName = "BELAMONTE VALVERDE Allechandro Jesus";
string[] words = fullName.Split(' ');
StringBuilder sb = new StringBuilder();
foreach (string word in words)
if (word.ToUpper() == word)
{
sb.Append(word + " ");
}
else
break; // That's assuming you will never have a last name's part after a first name's part :p
if (sb.Length > 0)
sb.Length--; // removes the last " " added in the loop, but maybe you want it ;)
Console.WriteLine(sb.ToString());