zoukankan      html  css  js  c++  java
  • 关于去掉字符串中最后一个符号的实例

    前几天在项目中遇到一个小问题,因为造成了困扰,且遇到的次数也比较多,所以觉得记录下来,给今后备用:

     

    1.当字符串以逗号分隔,最后一个可能存在逗号时,可用如下方式解决:

    eg:

    string name="test1,test2,test3,test4" 或者

    string name="test1,test2,test3,test4,"

    name.TrimEnd(','); //如果最后一位数为逗号,则去掉最后字符

    2.当字符串的最后一个字符确定为逗号,且想去掉最后一个字符时,可用如下方式解决:

    a.通过LastIndexOf取得最后一位字符Remove掉:eg:

    string name="test1,test2,test3,test4,"

    name.Remove(name.LastIndexOf(","))

    b.通过计算长度,再用subString截取除最后一个字符以外的字符串:eg:

    string name="abcd,";     

    name=name.subString(0,name.length-1);  //name.length=5;

    name="abcd"    

    c.通过函数EndsWith来判断最后一个字符是否为逗号,如果是则移除,eg:

    string name= name.EndsWith(",") ? name.Remove(name.Length - 1, 1) : name;      

     

    3.字符串以逗号分隔,最后一个可能存在逗号,且字符串中包含空格时,可用如下方式解决:

    eg:

    string name="test 100, test2 200,test3 300" 或者

    string name="test 100, test2 200,test3 300," 

    a.name.Join(",", "test 100, test2 200,test3 300,".Split(new char[1] { ',' }, System.StringSplitOptions.RemoveEmptyEntries));    

    b.name =name.Trim(',', ' '); //从当前对象移除数组中指定的一组字符的所有前导匹配项和尾部匹配项

     PS:Trim方法重载,name.Trim()是去掉字符串的前后空格

  • 相关阅读:
    某公司基于FineBI数据决策平台的试运行分析报告
    perl AnyEvent
    perl 微信 获取消息
    公司里的人际界线——北漂18年(41)
    perl URLencode URLdecode的方法
    Exception:org.eclipse.m2e.wtp.MarkedException: Unable to configure OHBC
    获取DIV内部内容报错
    JsViews Error:Unknown template:“#projectData”
    jQuery获取checkbox选中的值
    nginx mongodb相关配置
  • 原文地址:https://www.cnblogs.com/sunny0515/p/3309575.html
Copyright © 2011-2022 走看看