用破折号格式化字符串

时间:2010-10-19 13:28:39

标签: c# .net string.format

我有一个压缩的字符串值,我正在从导入文件中提取。我需要将其格式化为包裹编号,格式如下:##-##-##-###-###。因此,字符串“410151000640”应变为“41-01-51-000-640”。我可以使用以下代码执行此操作:

String.Format("{0:##-##-##-###-###}", Convert.ToInt64("410151000640"));

但是,字符串可能不是所有数字;它可能有一两个字母,因此转换为int将失败。有没有办法在字符串上执行此操作,以便每个字符(无论是数字还是字母)都能正确适合格式?

6 个答案:

答案 0 :(得分:24)

Regex.Replace("410151000640", @"^(.{2})(.{2})(.{2})(.{3})(.{3})$", "$1-$2-$3-$4-$5");

或稍短的版本

Regex.Replace("410151000640", @"^(..)(..)(..)(...)(...)$", "$1-$2-$3-$4-$5");

答案 1 :(得分:10)

我会通过拥有自己的格式化方法来解决这个问题,只要您知道“地块编号”始终符合特定规则即可。

public static string FormatParcelNumber(string input)
{
  if(input.length != 12)
     throw new FormatException("Invalid parcel number. Must be 12 characters");

  return String.Format("{0}-{1}-{2}-{3}-{4}",
                input.Substring(0,2),
                input.Substring(2,2),
                input.Substring(4,2), 
                input.Substring(6,3), 
                input.Substring(9,3));
}

答案 2 :(得分:3)

这适用于您的情况:

string value = "410151000640";
for( int i = 2; i < value.Length; i+=3){
  value = value.Insert( i, "-");
}

现在value包含插入破折号的字符串。

修改

我刚刚看到你在每一秒钟之间都没有破折号,这需要一个小的调整(并且让我有点笨拙而且我害怕)

string value = "410151000640";
for( int i = 2; i < value.Length-1; i+=3){
  if( value.Count( c => c == '-') >= 3) i++;
  value = value.Insert( i, "-");
}

答案 3 :(得分:2)

如果是UI的一部分,您可以在MaskedTextProvider

中使用System.ComponentModel
    MaskedTextProvider prov = new MaskedTextProvider("aa-aa-aa-aaa-aaa");
    prov.Set("41x151000a40");
    string result = prov.ToDisplayString();

答案 4 :(得分:0)

如果我正确地解释你正在寻找一个删除字符串中所有字母的函数,不是吗?

我已经动态创建了这个,也许你可以把它转换成c#,如果你正在寻找它:

Dim str As String = "410151000vb640"
str = String.Format("{0:##-##-##-###-###}", Convert.ToInt64(MakeNumber(str)))


Public Function MakeNumber(ByVal stringInt As String) As String
    Dim sb As New System.Text.StringBuilder
    For i As Int32 = 0 To stringInt.Length - 1
        If Char.IsDigit(stringInt(i)) Then
            sb.Append(stringInt(i))
        End If
    Next
    Return sb.ToString
End Function

答案 5 :(得分:0)

这是带有一些实用程序的简单扩展方法:

    2018-07-27 19:19:34.833  WARN 10809 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: username cannot be null
2018-07-27 19:19:34.862 ERROR 10809 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: username cannot be null
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:379) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1348) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:578) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.2.RELEASE.jar:2.0.2.RELEASE]
    at com.my.app.MyApplication.main(MyApplication.java:10) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_171]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_171]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_171]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_171]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.0.2.RELEASE.jar:2.0.2.RELEASE]
Caused by: java.lang.IllegalArgumentException: username cannot be null
    at org.springframework.util.Assert.notNull(Assert.java:193) ~[spring-core-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.core.userdetails.User$UserBuilder.username(User.java:377) ~[spring-security-core-5.0.5.RELEASE.jar:5.0.5.RELEASE]
    at com.my.app.config.SecurityConfig.configureGlobal(SecurityConfig.java:52) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_171]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_171]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_171]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_171]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:699) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    ... 22 common frames omitted

按以下方式使用它:

    public static string WithMask(this string s, string mask)
    {
        var slen = Math.Min(s.Length, mask.Length);
        var charArray = new char[mask.Length];
        var sPos = s.Length - 1;
        for (var i = mask.Length - 1; i >= 0 && sPos >= 0;)
            if (mask[i] == '#') charArray[i--] = s[sPos--];
            else
                charArray[i] = mask[i--];
        return new string(charArray);
    }

您可以将其与任何字符串一起使用,并且将插入掩码中除#以外的任何字符。遮罩将从右到左起作用。您可以根据需要将其调整为其他方式。

玩得开心。