Simple get string (ignore numbers at end) in C#

痞子三分冷 提交于 2019-12-10 17:04:38

问题


I figure regex is overkill also it takes me some time to write some code (i guess i should learn now that i know some regex).

Whats the simplest way to separate the string in an alphanumeric string? It will always be LLLLDDDDD. I only want the letters(l's), typically its only 1 or 2 letters.


回答1:


TrimEnd:

string result = input.TrimEnd(new char[]{'0','1','2','3','4','5','6','7','8','9'});
// I'm sure using LINQ and Range can simplify that.
// also note that a string like "abc123def456" would result in "abc123def"

But a RegEx is also simple:

string result = Regex.Match(input,@"^[^\d]+").Value;



回答2:


I prefer Michael Stum's regex answer, but here's a LINQ approach as well:

string input = "ABCD1234";
string result = new string(input.TakeWhile(c => Char.IsLetter(c)).ToArray());



回答3:


You can use a regular expression that matches the digits to remove them:

input = Regex.Replace(input, "\d+$", String.Empty);

The old fashioned loop isn't bad either, it should actually be the fastest solution:

int len = input.Length;
while (input[len-1] >= '0' && input[len-1] <= '9') len--;
input = input.Substring(0, len);



回答4:


They've got it - note the good solutions use the not operator to employ your problem description: "Not numbers" if you had the numbers at the front seems from my limited gains that you have to have what is called capturing groups to get past whatever it is on the front-end of the string. The design paradigm I use now is not delimiter character, followed by delimiter character, followed by an opening brace.

That results in needing a delimiter character that is not in the result set, which for one thing can be well established ascii values for data-delimitersl eg 0x0019 / 0x0018 and so on.



来源:https://stackoverflow.com/questions/1484198/simple-get-string-ignore-numbers-at-end-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!