如何在一个字符串计数特殊字符 [英] how to count special character in a string

查看:97
本文介绍了如何在一个字符串计数特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/11238184/string-functions-how-to-count-delimiter-in-string-line\">String功能如何计算的串线定界符



  

我有一个字符串作为海峡=一$ $的两个三个$四!5 @ 6 $现在怎么样用java code算在该字符串$的总数。



解决方案

使用的replaceAll:

 字符串str =一$ $的两个三个$四五@ 6 $!;    诠释计数= str.length() -  str.replaceAll(\\\\ $,)的长度();    的System.out.println(完成:+计数);

打印:

 完成:4

使用的替换而不是的replaceAll 资源密集型会少些。我只是把它展示给你的的replaceAll ,因为它可以搜索正则表达式的模式,这就是我用它为最。

请注意:使用的replaceAll 我要逃跑的 $ ,但是替换有没有这样的需要:

  str.replace($);
str.replaceAll(\\\\ $);

Possible Duplicate:
String Functions how to count delimiter in string line

I have a string as str = "one$two$three$four!five@six$" now how to count Total number of "$" in that string using java code.

解决方案

Using replaceAll:

    String str = "one$two$three$four!five@six$";

    int count = str.length() - str.replaceAll("\\$","").length();

    System.out.println("Done:"+ count);

Prints:

Done:4

Using replace instead of replaceAll would be less resource intensive. I just showed it to you with replaceAll because it can search for regex patterns, and that's what I use it for the most.

Note: using replaceAll I need to escape $, but with replace there is no such need:

str.replace("$");
str.replaceAll("\\$");

这篇关于如何在一个字符串计数特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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