Number of characters in string java

Number of characters in string java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

How to count characters in a string in Java?

A String is a sequence of characters. To count the characters in a string is to count the total number of characters excluding whitespace in the string. For example, if the string is str = «Confidence», then the total number of characters in str is 10. Few methods to count the characters in a string are discussed below.

Counting characters in a string using length() method

We can find the total characters in a string using the length() method. To do this task, after declaring the string, first we replace all the whitespace in the string with an empty character using replace() method, then we find the string length using length() method that gives the total characters in the string.

Total number of characters in the string is: 14

Counting characters in a string using for loop

We can count the total number of characters in a string using for loop. To count the characters using for loop, first we declare a count variable. We find the string length using length() method. Then we iterate through the entire string using for loop and increment the count variable for each character in the string.

Читайте также:  Javascript convert time to unix time

This method does not include white space while counting.

String str = "Secret diary"; int count = 0; // counts each character except space for (int i = 0; i < str.length(); i++) < if (str.charAt(i) != ' ') count++; >System.out.println("Total number of characters in the string is: " + count);
Total number of characters in the string is: 11

Counting characters in a string using while loop

Using while, we iterate from index position 0 till length — 1 of the string and increment the count variable for each character in the string. This method does not count whitespace.

String str = "Shopping"; int count = 0, i = 0; // counts each character in string except space while (i < str.length()) < if (str.charAt(i) != ' ') < count++; >i++; > System.out.println("Total number of characters in the string is: " + count);
Total number of characters in the string is: 8

Counting characters in a string using Java 8 stream

The chars() and the count() method of the Java 8 streams is can be used to count the total characters in the string, but it includes whitespace also. So we use the filter() method to exclude the whitespace and count the remaining characters.

String str = "Java streams"; long result = str.chars().filter(ch -> ch != ' ').count(); System.out.println("Total number of characters in the string is: " + result);
Total number of characters in the string is: 11

Источник

Count Characters in a String in Java

Count Characters in a String in Java

  1. Use String.length() to Count Total Characters in a Java String
  2. Use Java 8 Stream to Count Characters in a Java String
  3. Use Loop and charAt() to Count a Specific Character in a Java String

Today, we will introduce multiple ways to count the characters in a given Java string. We will count the total characters and the specific characters.

Читайте также:  Дано трехзначное число определить равен ли квадрат этого числа сумме кубов его цифр питон

Use String.length() to Count Total Characters in a Java String

The most common practice to get the total count of characters in a Java string is to use the length() method. In the below code, we have a string exampleString and will use exampleString.length() to get this string’s total length.

The output shows that there are 28 characters in exampleString while there are only 23 characters. It happens because String.length() counts the whitespaces too. To tackle this problem, we can use the replace() function to replace all the whitespaces with an empty character that is not counted. Finally, we can get the length of the string without any whitespaces, which is 23.

public class CountCharsInString   public static void main(String[] args)    String exampleString = "This is just a sample string";   int stringLength = exampleString.length();   System.out.println("String length: " + stringLength);   int stringLengthWithoutSpaces = exampleString.replace(" ", "").length();  System.out.println("String length without counting whitespaces: " + stringLengthWithoutSpaces);  > > 
String length: 28 String length without counting whitespaces: 23 

Use Java 8 Stream to Count Characters in a Java String

Another way to count all the characters in a string is to use the String.chars().count() method that returns the total number of characters in the string, but including whitespaces. As chars() is a stream, we can use the filter() method to ignore the whitespaces. filter(ch -> ch != ‘ ‘) checks every character and if it founds a whitespace it will filter it out.

public class CountCharsInString   public static void main(String[] args)    String exampleString = "This is just a sample string";   long totalCharacters = exampleString.chars().filter(ch -> ch != ' ').count();   System.out.println("There are total " + totalCharacters + " characters in exampleString");  > > 
There are total 23 characters in exampleString 

Use Loop and charAt() to Count a Specific Character in a Java String

We have been counting the total characters in a string, but the below example shows the method to count a specific character in the string. Our goal is to get the number of i in exampleString . To achieve this, we used a loop that runs until the string’s end.

We create two additional variables: totalCharacters that will hold the count, and temp that will hold every individual character using exampleString.charAt(i) . To check our character’s occurrence, we will compare temp with our character to check if they match. If it finds a match, then totalCharacters will be incremented by one. Once the loop is over, we can see the total occurrences of our character in the string.

public class CountCharsInString   public static void main(String[] args)    String exampleString = "This is just a sample string";   int totalCharacters = 0;  char temp;  for (int i = 0; i  exampleString.length(); i++)    temp = exampleString.charAt(i);  if (temp == 'i')  totalCharacters++;  >   System.out.println("i appears " + totalCharacters + " times in exampleString");  > > 
i appears 3 times in exampleString 

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

Related Article — Java String

Related Article — Java Char

Copyright © 2023. All right reserved

Источник

Оцените статью