[java] How to check how many letters are in a string in 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)?

This question is related to java string

The answer is


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

edit

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++;
}

where TestCase can be isLetter( ), isDigit( ), etc.

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


To answer your questions in a easy way:

    a) String.length();
    b) String.charAt(/* String index */);

If you are counting letters, the above solution will fail for some unicode symbols. For example for these 5 characters sample.length() will return 6 instead of 5:

String sample = "\u760c\u0444\u03b3\u03b5\ud800\udf45"; // ???e

The codePointCount function was introduced in Java 1.5 and I understand gives better results for glyphs etc

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

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


1) To answer your question:

  String s="Java";
  System.out.println(s.length()); 

Questions with java tag:

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error Instantiating a generic type When to create variables (memory management) java doesn't run if structure inside of onclick listener String method cannot be found in a main class method Are all Spring Framework Java Configuration injection examples buggy? Calling another method java GUI I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array Java and unlimited decimal places? Read input from a JOptionPane.showInputDialog box Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable Two Page Login with Spring Security 3.2.x Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java) Got a NumberFormatException while trying to parse a text file for objects Best way for storing Java application name and version properties Call japplet from jframe FragmentActivity to Fragment Comparing two joda DateTime instances Maven dependencies are failing with a 501 error IntelliJ: Error:java: error: release version 5 not supported Has been compiled by a more recent version of the Java Runtime (class file version 57.0) Why am I getting Unknown error in line 1 of pom.xml? Gradle: Could not determine java version from '11.0.2' Error: Java: invalid target release: 11 - IntelliJ IDEA Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Why is 2 * (i * i) faster than 2 * i * i in Java? must declare a named package eclipse because this compilation unit is associated to the named module How do I install Java on Mac OSX allowing version switching? How to install JDK 11 under Ubuntu? Java 11 package javax.xml.bind does not exist IntelliJ can't recognize JavaFX 11 with OpenJDK 11 Difference between OpenJDK and Adoptium/AdoptOpenJDK OpenJDK8 for windows How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Find the smallest positive integer that does not occur in a given sequence Error: JavaFX runtime components are missing, and are required to run this application with JDK 11 How to uninstall Eclipse? Failed to resolve: com.google.firebase:firebase-core:16.0.1 How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Questions with string tag:

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript How to change the datetime format in pandas How to write to a CSV line by line? convert string to number node.js "error: assignment to expression with array type error" when I assign a struct field (C) Remove 'b' character do in front of a string literal in Python 3 Ruby: How to convert a string to boolean What does ${} (dollar sign and curly braces) mean in a string in Javascript? How do I make a new line in swift converting json to string in python PHP - remove all non-numeric characters from a string C# - How to convert string to char? How can I remove the last character of a string in python? Converting std::__cxx11::string to std::string How to convert string to date to string in Swift iOS? Convert time.Time to string TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3 How can I capitalize the first letter of each word in a string using JavaScript? Best way to verify string is empty or null Hive cast string to date dd-MM-yyyy Check for special characters in string How to convert any Object to String? Print "\n" or newline characters as part of the output on terminal Set the maximum character length of a UITextField in Swift How do I convert a Python 3 byte-string variable into a regular string? What does $ mean before a string? Delete the last two characters of the String Splitting a string into separate variables Figure out size of UILabel based on String in Swift Matching strings with wildcard How do I concatenate strings? Print very long string completely in pandas dataframe Check string for nil & empty Convert float to string with precision & number of decimal digits specified? How do I print my Java object without getting "SomeType@2f92e0f4"? enum to string in modern C++11 / C++14 / C++17 and future C++20 How should I remove all the leading spaces from a string? - swift Convert array to JSON string in swift Swift extract regex matches Convert a file path to Uri in Android How would I get everything before a : in a string Python