如何检查java中字符串中有多少个字母? [英] How to check how many letters are in a string in java?
问题描述
如何检查Java字符串中有多少个字母?
How do you check how many letters are in a Java string?
如何检查字符串中某个位置的字母(即第二个字母)字母的字母)?
How do you check what letter is in a certain position in the string (i.e, the second letter of the string)?
推荐答案
A)
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
检查针对您的测试用例的每个索引。
If you want to count the number of a specific type of characters in a String
, then a simple method is to iterate through the String
checking each index against your test case.
int charCount = 0;
char temp;
for( int i = 0; i < str.length( ); i++ )
{
temp = str.charAt( i );
if( temp.TestCase )
charCount++;
}
其中 TestCase
可以是 isLetter()
, isDigit()
等。
或者,如果您只想计算除空格之外的所有内容,请在中检查
,如 temp!=''
Or if you just want to count everything but spaces, then do a check in the if
like temp != ' '
B)
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
这篇关于如何检查java中字符串中有多少个字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!