我如何使用string.split或substring函数 [英] How do I use a string.split or substring function

查看:77
本文介绍了我如何使用string.split或substring函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量,它正在使用excel电子表格中的名称填充。然而,这些名称是手动输入的,因此没有最佳格式。



如何使用

  string  .split 

 substring 

以考虑以下某些示例:



J ane Doe

约翰史密斯



我看了看在msdn示例但是并不太了解它们。当我调试我的代码变量Worker =John Smith时,我想把这个词分成名字和姓氏,同时修剪任何多余的空格。



任何想法?

解决方案

如果你想把约翰史密斯变成约翰,史密斯和J ane Doe变成J ane ,Doe然后分裂不适合你 - 它将永远分裂在每个空间,因为J ane Doe将变成J,ane,Doe。



子串可以做到:

  string  input =   J ane Doe; 
int lastSpace = input.LastIndexOf(' );
string firstName = input.SubString( 0 ,lastSpace);
string lastName = input.Substring(lastSpace);



或者你可以使用正则表达式:

(?< firstName>。*)\((< lastName> [AZ] [a-zA-Z  - ] *)

通过查找最终的大写单词来捕获姓氏。


I have a variable which is being populated with names from an excel spreadsheet. The names however were manually entered and because of that don't have the best format.

How can use

string.split

or

substring

to account for some of the following examples:

"J ane Doe"
"John Smith"

I've taken a look at the msdn examples but didn't quite understand them. When I debug my code the variable Worker = "John Smith" but I'd like to break the word into first and last name while also trimming any excess spaces.

Any ideas?

解决方案

If you want to break "John Smith" into "John", "Smith" and "J ane Doe" into "J ane", "Doe" then split is not for you - it will always split on each space, for "J ane Doe" will become "J", "ane", "Doe".


Substring can do it:

string input = "J ane Doe";
int lastSpace = input.LastIndexOf(' ');
string firstName = input.SubString(0, lastSpace);
string lastName = input.Substring(lastSpace);


Or you could use a Regex:

(?<firstName>.*)\s(?<lastName>[A-Z][a-zA-Z-]*)


Which would capture the last name by looking for the final capitalized word.


这篇关于我如何使用string.split或substring函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆