通过字符类型确定子字符串的结束点

时间:2018-02-04 08:05:52

标签: c#

很抱歉,我很难为这篇文章找到一个合适的标题。如果标题不清楚则是一个例子。

我有许多字符串遵循这样的格式

"Application has been dispatched to the client 5  business day(s) ago. Signed application has not been received"

我想将其子串到5号。

所以结果将是

 "Application has been dispatched to the client"

但是,我并不总是知道数字值

之前有多少个字符

某些字符串具有不同的消息,但结构类似。总有一个数字。

另一个例子

"Client signed the application 13 day(s) ago."

现在在这一个中,我想得到以下输出

"Client signed the application"

基本上,我需要一种方法来获取所有内容,直到数值。

我该怎么做?

希望这是明确的,并提前感谢!

干杯!

4 个答案:

答案 0 :(得分:1)

老实说,你可以使用split()字符串将字符串值转换为数组

例如:

var str = "Client signed the application 13 day(s) ago"; 
var res = str.Split(' '); // split when space found
Console.WriteLine(res[0]); // output value when array index at 0

所以,输出应该是:

Client 

之后你只需将数据循环到数组中,当找到可以转换为整数的字符串数据时,循环必须停止

        int number, index = 0;

        bool result = false; 

        while (result == false)
        {
            Console.WriteLine(res[index]);
            index++;
            result = Int32.TryParse(res[index], out number);
        }

最后输出应该是

Client 
signed 
the 
application

希望我的回答可以帮到你

答案 1 :(得分:1)

听起来你需要一些正则表达式。既然你想要数字,这应该工作:

var regex = new Regex(@" \d+");
var result = input.Substring(0, regex.Match(input).Index));

(假设input是你的字符串)。这将从开始直到第一个数字为子串,不包括空格。

请注意,如果字符串没有数字,则结果将为空。如果您希望它返回该实例中的整个字符串,您可以使用if语句来测试匹配索引是否为零。

答案 2 :(得分:1)

我喜欢函数式编程,所以我想先在F#中解决这个问题。以下是我提出的建议:

let findNumber (s : string) =
    let rec loop i =
        if i >= s.Length then -1
        elif Core.char.IsDigit s.[i] then i
        else loop (i + 1)
    loop 0

let truncateAtNumber s =
    match findNumber s with
    | -1 -> s
    | p -> (s.Substring (0, p)).Trim ()

简短而干净。但是,我很惊讶C#翻译实际上更短(编辑:现在更短):

static string TruncateAtNumber(this string s)
{
    for (int i = 0; i < s.Length; i++)
        if (char.IsDigit(s[i]))
            return s.Substring(0, i).Trim();
    return s;
}

答案 3 :(得分:1)

string result = Regex.Match(str, @"\D*").Value;

\D匹配任何非数字字符,*匹配0次或更多次。

或者更短一些:

string result = Regex.Split(str, @"\d")[0];
相关问题