Java >> Tutoriel Java >  >> Tag >> String

Méthode Java String length () avec exemple de programme

Qu'est-ce que la fonction de longueur de chaîne Java ?

La fonction Longueur de chaîne() est utilisé pour trouver la longueur d'une chaîne en Java. Cette chaîne Length() renvoie le nombre de caractères présents dans toute chaîne qui est égal au nombre de caractères Unicode 16 bits dans la chaîne.

Remarque :

  • Si la chaîne d'entrée est vide, la fonction renverra 0
  • La fonction comptera l'espace comme un caractère

Syntaxe

public int length()

Paramètres

La longueur de chaîne() la fonction ne prend aucun paramètre

Valeur de retour

Cette longueur de chaîne() La fonction renvoie une valeur entière impliquant le nombre de caractères dans la chaîne.

Exemple

Programme pour trouver la longueur d'une chaîne en Java

//Java program to find the length of string

//Import the java util package

import java.util.Scanner;

//Main Class of the program
public class Main
{
    //Main Method of the program
    public static void main(String[] args) {
        //Creating the Scanner Class object
        Scanner scan = new Scanner(System.in);
        //Giving a hint to the user,What to enter
        System.out.print("Enter the string : ");
        //Taking input from user
        String string_1 = scan.nextLine();
        //Finding the length of string
        System.out.println("The string " + string_1 + " has length of "+string_1.length() + " Character");

    }
}

Sortie

Enter the string : STechies
The string STechies has length of 8 Character


Balise Java