如何检查java中的字符串中有多少个字母?

新手上路,请多包涵

如何检查 Java 字符串中有多少个字母?

如何检查字符串中某个位置的字母(即字符串的第二个字母)?

原文由 tussya 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 652
2 个回答

一个)

 String str = "a string";
int length = str.length( ); // length == 8

http://download.oracle.com/javase/7/docs/api/java/lang/String.html#length%28%29

编辑

如果您想计算 String 中特定类型字符的数量,那么一种简单的方法是遍历 String 根据您的测试用例检查每个索引。

 int charCount = 0;
char temp;

for( int i = 0; i < str.length( ); i++ )
{
    temp = str.charAt( i );

    if( temp.TestCase )
        charCount++;
}

其中 TestCase 可以是 isLetter( ) , isDigit( ) 等。

或者,如果您只想计算除空格以外的所有内容,请在 if 中进行检查,例如 temp != ' '

二)

 String str = "a string";
char atPos0 = str.charAt( 0 ); // atPos0 == 'a'

http://download.oracle.com/javase/7/docs/api/java/lang/String.html#charAt%28int%29

原文由 ssell 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您正在计算字母,上述解决方案对于某些 unicode 符号将失败。例如,对于这 5 个字符,sample.length() 将返回 6 而不是 5:

 String sample = "\u760c\u0444\u03b3\u03b5\ud800\udf45"; // 瘌фγε𐍅

codePointCount 函数是在 Java 1.5 中引入的,我知道它可以为字形等提供更好的结果

sample.codePointCount(0, sample.length()) // returns 5

http://globalizer.wordpress.com/2007/01/16/utf-8-and-string-length-limitations/

原文由 ThomasMH 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题