Métodos de String em Java

Neste artigo, discutiremos os métodos de string Java mais comumente usados ​​com exemplos.

Em Java , strings são um tipo de dados comumente usado e a classe String oferece um conjunto de métodos integrados para manipular strings

Métodos de String Java



Métodos de String Java

A classe String fornece uma coleção de métodos predefinidos que podem ser utilizados para manipular strings.

Métodos de String Visão geral Tipo de retorno
charAt() Especifica uma posição de caractere (índice) e a retorna. Caracteres
codePointAt() No índice especificado, esta função fornece o Unicode do caractere int
codePointBefore() Uma representação Unicode do caractere antes do índice especificado é exibida int
codePointCount() Conta quantos valores Unicode são encontrados em uma string e exibe o número. int
comparado a() Compara duas strings em ordem alfabética int
compareToIgnoreCase() Ignora diferenças de maiúsculas e minúsculas ao comparar duas strings semanticamente int
concat() O método append anexa uma string ao final de outra string Corda
contém() Detecta a presença de uma sequência de caracteres em uma string boleano
conteúdoEquals() A função detecta se uma string contém exatamente a mesma sequência de caracteres que o CharSequence ou StringBuffer especificado boleano
copyValueOf() Este método gera uma String contendo os caracteres do array de caracteres Corda
termina com() Uma string é verificada para ver se ela termina com o(s) caractere(s) desejado(s) sendo pesquisado(s) boleano
é igual a() Uma comparação é feita entre duas strings. A função retorna true se as strings forem iguais e false caso contrário. boleano
equalsIgnoreCase() Uma comparação é realizada entre duas strings, independentemente do caso boleano
formatar() Atribui a string de formato, localidade e argumentos a uma string formatada Corda
getBytes() Faz uso do conjunto de caracteres nomeado para codificar esta String em um conjunto de bytes, adicionando o resultado em uma nova matriz de bytes byte[]
getChars() Os caracteres são duplicados de uma string para uma matriz de caracteres vazio
hashCode() Esta função gera o código hash da string int
índice de() Esta função exibe a primeira ocorrência de uma string de caracteres especificados int
estagiário() Esta função retorna a forma padronizada do objeto string Corda
está vazia() Uma string é verificada para ver se está vazia ou não boleano
últimoIndexOf() Em uma string, esta função retorna a posição da última aparição dos caracteres especificados int
comprimento() O comprimento da string é calculado como resultado de um argumento especificado int
partidas() Usando uma expressão regular, esta função pesquisa uma string em busca de correspondências e as exibe boleano
offsetByCodePoints() Esta função fornece o índice dentro desta String que é compensado pelos pontos de código codePointOffset do índice fornecido. int
regiãoCorrespondências() Um teste para determinar se duas strings são idênticas ou não boleano
substituir() Retorna uma nova string que substitui os valores especificados em uma string com base em uma pesquisa de string para um valor especificado. Corda
substituirPrimeiro() As substrings que correspondem à expressão regular fornecida são substituídas pela substituição fornecida em sua primeira ocorrência nas strings Corda
substitua tudo() Isso substitui todas as substrings dessa string pela substituição fornecida na expressão regular. Corda
dividir() Matrizes de substrings são criadas dividindo uma string Corda[]
começa com() Uma string é verificada para ver se ela começa com os caracteres especificados boleano
subsequência() Uma subsequência arbitrária da sequência de caracteres é apresentada CharSequence
substring() Substrings da string especificada são geradas como novas strings Corda
toCharArray() Cria uma matriz de caracteres considerando a string fornecida Caracteres[]
toLowerCase() A função transforma uma string em letras minúsculas Corda
para sequenciar() Retorna o valor de um objeto do tipo String Corda
toUpperCase() Uma string é alterada para letras maiúsculas Corda
aparar() Uma função de remoção de espaço em branco de ponta a ponta Corda
valor de() Esta função gera uma string correspondente ao valor especificado Corda

Método Java String charAt ()

Os caracteres em índices especificados em uma string são retornados pelo método charAt() .

O primeiro caractere tem índice 0, o segundo caractere tem índice 1, etc.

Sintaxe

public char charAt(int index)

Parâmetros

O índice do caractere a ser retornado é um valor int .

O seguinte programa mostra o número de índice da letra J:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
public class Main {
public static void main(String[] args) {
String mrx="You are learning Java String Methods from Mr.Examples";
System.out.println("Character at index number 17 is: "+mrx.charAt(17));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("\nEnter String here: ");
String mrx=input.nextLine();
System.out.println("\nEnter Index Number of the Alphabet here: ");
int ample= input.nextInt();
System.out.println("—————————– Result ———————————–");
System.out.println("\n Entered String: "+mrx);
System.out.println(" Index Number entered: "+ample);
System.out.println(" Character at index number ( "+ample+" ) is: "+mrx.charAt(ample));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String codePointAt()

Uma string contendo o caractere no índice especificado será retornada com o valor Unicode usando o método codePointAt() .

O primeiro caractere tem índice 0, o segundo caractere tem índice 1, etc.

Sintaxe

public int codePointAt(int index)

Parâmetros

index é um número inteiro que recebe o número do índice.

O seguinte programa mostra o código ASCII da variável (e) como:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
public class Main {
public static void main(String[] args) {
String mrx="Greetings ! We are learning about the Ascii Code methods of Java String ";
System.out.println("Character's Ascii code at index number 15 (e) is: "+mrx.codePointAt(15));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Aqui, o programa fornecido mostra o código ASCII de qualquer alfabeto conforme a entrada do usuário:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("\nEnter String here: ");
String mrx=input.nextLine();
System.out.println("\nEnter Index Number of the Alphabet here: ");
int ample= input.nextInt();
System.out.println("—————————– Ascii Code Calculator ———————————–");
System.out.println("\n Entered String: "+mrx);
System.out.println(" Index Number entered: "+ample);
System.out.println(" Character's Ascii Code at index number ( "+ample+" ) is: "+mrx.codePointAt(ample));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String codePointBefore()

Usando o método codePointBefore() , você pode recuperar o valor Unicode do caractere antes do índice especificado.

Inicialmente, o primeiro caractere é indexado como 0, depois o segundo caractere é indexado como 1 e assim por diante.

 

Importante: Se você inserir o valor 0, ocorrerá um erro, pois é um número negativo (inalcançável).

Parâmetros

Um valor do tipo int representando o índice Unicode é exibido.

O código a seguir mostra o código ASCII de (M) que é 77:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Main {
public static void main(String[] args) {
String ample="Mr. Examples";
System.out.println("The Ascii Code of M before the specified index is given as: "+ample.codePointBefore(1));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

O exemplo a seguir mostra o funcionamento múltiplo do método codePointBefore() :

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Main {
public static void main(String[] args) {
String mrx = "Mr.";
String ample = "Examples";
System.out.println("The Ascii Code of r is shown using the codePointBefore() method: " + mrx.codePointBefore(2));
System.out.println("The Ascii Code of x is shown using the codePointBefore() method: " + ample.codePointBefore(2));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String codePointCount()

Uma matriz de valores Unicode é contada usando o método codePointCount() .

Se você deseja especificar onde iniciar a pesquisa e onde finalizá-la, pode usar os parâmetros startIndex e endIndex.

Quanto ao primeiro caractere, seu índice é 0, depois 1, depois 2, etc.

Sintaxe

public int codePointCount(int startIndex, int endIndex)

Parâmetros

O startIndex é um valor inteiro que indica onde a string começa, o endIndex é um valor inteiro que indica onde a string termina.

O exemplo a seguir mostra os unicodes de alfabetos até um intervalo:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Main {
public static void main(String[] args) {
String mrx_ample = "Hey User !! I hope you will be having fun learning String methods using the codePointCount() method: ";
int result =mrx_ample.codePointCount(2,7);
System.out.println("The Count of alphabets that contain the Unicode upto the range is shown as: " +result);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter the String here: ");
String mrx=input.nextLine();
System.out.println("Enter Starting Index: ");
int ample1=input.nextInt();
System.out.println("Enter Ending Index: ");
int ample2=input.nextInt();
System.out.println("\nThe Count of Alphabets having the Ascii Code from index "+ample1+" to "+ample2+" is: "+mrx.codePointCount(ample1,ample2));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String compareTo()

Comparar duas strings em ordem alfabética é o propósito do método compareTo() .

Cada caractere na string é comparado com base em seu valor Unicode.

Se a string for igual à outra string, o método retorna 0.

Se a string for menor que a outra string (menos caracteres), um valor menor que 0 será retornado; se a string for maior que a outra string, um valor maior que 0 será retornado.

Dica : compareToIgnoreCase() compara duas strings em ordem alfabética, ignorando as diferenças entre maiúsculas e minúsculas.
Dica : Uma string pode ser comparada sem levar em consideração os valores Unicode usando o método equals() .

Sintaxe

public int compareTo(String mrx_string)
public int compareTo(Object object)

Parâmetros

String 2 representa a outra string que precisa ser comparada com uma string de texto

Object mostra que os objetos a serem comparados são representados por objetos

O seguinte programa mostra a comparação de duas strings:

Da mesma forma, também podemos comparar duas strings fornecidas pelo usuário da maneira abaixo:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Main {
public static void main(String[] args) {
String mrx="You are learning string compareTo() method from Mr.Examples";
String ample="This string differs from the string given above hence 1 is returned";
System.out.println("Result: "+mrx.compareTo(ample));
System.out.println("The Output of the Comparison will be greater than 0 as the both strings are distinct to each other and the second string is greater than the first ");
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Da mesma forma, também podemos comparar duas strings fornecidas pelo usuário da maneira abaixo:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter First Sentence here: ");
String mrx=input.nextLine();
System.out.println("Enter Second Sentence here: ");
String ample=input.nextLine();
int result=mrx.compareTo(ample);
if(result==0){
System.out.println("\nResult of Compare Method: "+result);
System.out.println("\nBoth Strings are equal to each other in terms of all characters and length");
}
else if(result>0){
System.out.println("\nResult of Compare Method: "+result);
System.out.println("\nBoth Strings are distinct to each other and the length of Sentence one is more than the Sentence two");
}
else{
System.out.println("\nResult of Compare Method: "+result);
System.out.println("\nBoth Strings are distinct to each other and length of First Sentence is less than the Second Sentence");
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String compareToIgnoreCase()

Usando o método compareToIgnoreCase() , duas strings podem ser comparadas lexicograficamente sem levar em consideração letras minúsculas ou maiúsculas.

Os caracteres na string são comparados usando seus valores Unicode convertidos em letras minúsculas.

0 é retornado se as strings forem iguais, independentemente das diferenças entre maiúsculas e minúsculas. Se a string for menor que outra string (menos caracteres), ela será retornada como um número menor que 0 e, se for maior que outra string, será retornada como um número maior que 0.

Sintaxe

public int compareToIgnoreCase(String my_string)

Parâmetros

my_string é usado como uma string de pesquisa, ignorando o caso que a string contém.

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Main {
public static void main(String[] args) {
String mrx="mrexamples";
String ample="MREXAMPLES";
System.out.println("The value is: "+mrx.compareToIgnoreCase(ample));
System.out.println("Gives Output as 0 because the Both strings are equal to each other irrespective of the case");
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

O programa fornecido recebe duas strings como entrada do usuário e informa se elas são iguais ou não, independentemente de suas maiúsculas e minúsculas, usando o método compareToIgnoreCase() :

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner my_input=new Scanner(System.in);
System.out.println("Enter First String here: ");
String mrx=my_input.nextLine();
System.out.println("Enter Second String here: ");
String ample=my_input.nextLine();
int mrx_result=mrx.compareToIgnoreCase(ample);
System.out.println("\n——————————— Result —————————————");
if (mrx_result==0){
System.out.println("\nResult: "+mrx_result);
System.out.println("\nThe both strings are equal to each other irrespective of their cases");
}
else if (mrx_result>0){
System.out.println("\nResult: "+mrx_result);
System.out.println("\nThe both strings are distinct and the string 1 is greater in length than string 2");
}
else{
System.out.println("\nResult: "+mrx_result);
System.out.println("\nThe both strings are distinct and the string 2 is greater in length than string 1");
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String concat ()

Uma string pode ser anexada a outra string usando o método concat() .

Sintaxe

public String concat(String mrx_string)

Parâmetros

Aqui, mrx_string mostra a string a ser anexada/unida com outra string.

O seguinte programa mostra a concatenação das strings mrx e ample:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Main
public static void main(String[] args) {
String mrx="Mr.";
String ample="Examples";
String concat_string=mrx.concat(ample);
System.out.println("String After Concatenation: "+concat_string);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

O seguinte programa mostra a junção de duas strings:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter String 1 here: ");
String mrx=input.nextLine();
System.out.println("Enter String 2 here: ");
String ample=input.nextLine();
String mrx_ample=mrx.concat(ample);
System.out.println("\n String 1: "+mrx+"\n String 2: "+ample+"\n After concatenation : "+mrx_ample);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

O método Java String contém ()

Um método string contains() verifica se uma sequência de caracteres existe em uma string ou não.

Se os caracteres existirem, true será retornado, caso contrário, false será retornado.

Sintaxe

public boolean contains(CharSequence mrx)

Parâmetros

CharSequence mrx procura os caracteres na string.

Uma interface chamada CharSequence é uma interface que permite uma sequência legível de valores char, que faz parte do pacote java.lang.
O exemplo dado mostra o funcionamento do método contains() :

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Main {
public static void main(String[] args) {
String mrx_string="Hey !! You are learning about contains() method included in Java String methods";
System.out.println("\nDoes the String contains the sequence { contains() } ?"+"\nAnswer: "+mrx_string.contains("contains()"));
System.out.println("\nDoes the String contains the sequence { included } ? "+"\nAnswer: "+mrx_string.contains("included"));
System.out.println("\nDoes the String contains the sequence { Python } ? "+"\nAnswer: "+mrx_string.contains("python"));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Da mesma forma, também podemos verificar se uma entrada do usuário contém uma sequência específica de caracteres:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
System.out.println("Enter String here: ");
String mrx=input.nextLine();
System.out.println("Enter Sequence of Characters to be searched : ");
CharSequence ample=input.nextLine();
if(mrx.contains(ample)){
System.out.println("\nResult: The Following Sequence {"+ample+"} is a part of String");
}
else{
System.out.println("\nResult: The Following Sequence {"+ample+"} does not belong to the corresponding String");
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String contentEquals()

Ao chamar contentEquals() , pode-se verificar se o conteúdo de uma string corresponde ao de uma string ou de um buffer de string.

A função retorna true se os caracteres existirem e false caso contrário.

Sintaxe

No método contentEquals() , existem dois métodos disponíveis:

public boolean contentEquals(StringBuffer mrx)
public boolean contentEquals(CharSequence ample)

Parâmetros

StringBuffer mrx é a string a ser procurada.
CharSequence ample contém uma sequência de caracteres a serem pesquisados ​​em ample.

Java.lang contém a classe StringBuffer, que é semelhante à classe String, mas permite modificações.

Java.lang possui uma interface chamada CharSequence, que representa uma sequência de valores char.

O programa fornecido mostra o funcionamento do método contentEquals() :

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Main {
public static void main(String[] args) {
String mrx="Mr.Examples";
System.out.println("\n--> Does the character sequence { Mr.Examples } a part of String ?");
System.out.println("Answer: "+mrx.contentEquals("Mr.Examples"));
System.out.println("\n--> Does the character sequence { Mr. } a part of String ?");
System.out.println("Answer: "+mrx.contentEquals("Mr."));
System.out.println("\n--> Does the character sequence { Examples } a part of String ?");
System.out.println("Answer: "+mrx.contentEquals("Examples"));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

O programa a seguir executa a mesma operação usando o método contentEquals() para pesquisar um bloco exato de caracteres usando a entrada do usuário:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
System.out.println("Enter String here: ");
String mrx=input.nextLine();
System.out.println("Enter the exact group of Characters to be searched : ");
CharSequence ample=input.nextLine();
if(mrx.contentEquals(ample)){
System.out.println("\nResult: The Following Sequence {"+ample+"} is a part of String");
}
else{
System.out.println("\nResult: The Following Sequence {"+ample+"} content does not belong to the corresponding String");
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String copyValueOf()

Usando o método copyValueOf() , você pode obter os caracteres de um array char como uma String.

Como resultado, esse método retorna um novo array String contendo os caracteres copiados do array anterior.

Sintaxe

public static String copyValueOf(char[] mrx, int ample, int count_mrx)

Parâmetros

O mrx consiste em uma matriz de caracteres.

O amplo é um valor int que representa o índice inicial do array char.

Um valor count_mrx representa o comprimento de uma matriz de caracteres como um int.

Os exemplos dados ilustram a cópia de caracteres de um array char para uma String:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Main {
public static void main(String[] args) {
char mrx []={'M','R','.','E','X','A','M','P','L','E','S'};
String ample="";
ample=ample.copyValueOf(mrx,0,11);
System.out.println(" After Successfully Copying the characters we get the new string as: "+ample);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Também podemos copiar todos os caracteres de um array char usando apenas o nome do array char no método copyValueOf() :

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Main {
public static void main(String[] args) {
char character[]={'J','A','V','A','-','S','T','R','I','N','G','-','M','E','T','H','O','D','S'};
String storing_mrx="";
String copying_String=storing_mrx.copyValueOf(character);
System.out.println("The String after successfully copying value of the Characters array is: "+copying_String);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String endsWith()

Usando o método endsWith(), você pode verificar se uma string termina com um ou mais caracteres específicos.

Dica : Se você quiser verificar se uma string começa com um ou mais caracteres individuais, use o método startsWith().

Sintaxe

public boolean endsWith(String mrx)

Nesse caso, mrx representa uma String que contém o(s) caractere(s) a ser(em) verificado(s).

O programa a seguir mostra a análise da string se ela termina com uma sequência específica ou não:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Main {
public static void main(String[] args) {
String mrx="Greetings Learner !! The topic of Discussion today is java string's endsWith() method";
System.out.println("\n--> Does the String mrx Ends with od ?");
System.out.println("Answer: "+mrx.endsWith("od"));
System.out.println("\n--> Does the String mrx Ends with method ?");
System.out.println("Answer: "+mrx.endsWith("method"));
System.out.println("\n--> Does the String mrx Ends with string ?");
System.out.println("Answer: "+mrx.endsWith("string"));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

O seguinte programa recebe uma string como uma entrada do usuário e informa se ela termina com uma sequência de caracteres:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter Any String here: ");
String mrx=input.nextLine();
System.out.println("Enter the sequence of the characters on which the given string terminates : ");
String ample=input.nextLine();
System.out.println("\n—————————————- Result ——————————————\n");
if(mrx.endsWith(ample)){
System.out.println("String Entered: "+mrx);
System.out.println("Ends with Characters: "+ample);
System.out.println("\n--> Matched !! the given String ends with:"+ample);
}
else{
System.out.println("String Entered: "+mrx);
System.out.println("Not Matched !! the given String does not ends with the characters: "+ample);
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String startsWith ()

Usando startWith(), você pode verificar se uma string começa com o caractere ou caracteres especificados.

Conselho : O método endsWith() é uma ferramenta conveniente para verificar se a string que você está verificando termina com o(s) caractere(s) especificado(s).

Sintaxe

public boolean startsWith(String mrx)

Parâmetros

Nesse caso, o mrx é simplesmente uma string contendo o(s) caractere(s) que você deseja verificar.

Os exemplos fornecidos verificam se a String fornecida começa com diferentes sequências de caracteres:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Main {
public static void main(String[] args) {
String ample="The String startsWith() methods is used to check if the corresponding Strings starts with the specific sequence of characters";
System.out.println("\n--> Does the String Ends with The ?");
System.out.println("Answer: "+ample.startsWith("The"));
System.out.println("\n--> Does the String Ends with Th ?");
System.out.println("Answer: "+ample.startsWith("Th"));
System.out.println("\n--> Does the String Ends with Mr. ?");
System.out.println("Answer: "+ample.startsWith("Mr."));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Da mesma forma , o seguinte programa pega uma string como uma entrada do usuário e a armazena, então pega outra entrada de string para os caracteres a serem pesquisados ​​na seguinte string e retorna a saída como verdadeiro ou falso:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter Any String here: ");
String mrx=input.nextLine();
System.out.println("Enter the sequence of the characters on which the given string starts : ");
String ample=input.nextLine();
System.out.println("\n—————————————- Result ——————————————\n");
if(mrx.startsWith(ample)){
System.out.println("String Entered: "+mrx);
System.out.println("Starts with Characters: "+ample);
System.out.println("\n--> Matched !! the given String starts with: "+ample);
}
else{
System.out.println("String Entered: "+mrx);
System.out.println("Not Matched !! the given String does not starts with the characters: "+ample);
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String equals ()

No método equals() , duas strings são comparadas para ver se são iguais e a saída é retornada como verdadeira. Se eles não forem iguais, false será retornado.

Conselho : Usar o método compareTo() é uma maneira confiável de comparar alfabeticamente duas strings.

Sintaxe

public boolean equals(Object mrx_String)

Parâmetros

Aqui mrx_String representa a segunda string a ser comparada com a primeira.

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Main {
public static void main(String[] args) {
String mrx="You are Learning About Java String method equals()";
String ample="You are Learning ";
String ample1="You are Learning About Java";
String ample2="You are Learning About Java String";
String ample3="You are Learning About Java String method";
String ample4="You are Learning About Java String method equals()";
System.out.println("\n-->Does mrx equals ample ??");
System.out.println("Answer: "+mrx.equals(ample));
System.out.println("\n-->Does mrx equals ample1 ??");
System.out.println("Answer: "+mrx.equals(ample1));
System.out.println("\n-->Does mrx equals ample2 ??");
System.out.println("Answer: "+mrx.equals(ample2));
System.out.println("\n-->Does mrx equals ample3 ??");
System.out.println("Answer: "+mrx.equals(ample3));
System.out.println("\n-->Does mrx equals ample4 ??");
System.out.println("Answer: "+mrx.equals(ample4));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Correspondentemente, o seguinte programa recebe duas strings diferentes como entrada do usuário e mostra se elas são iguais ou não:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter the String here: ");
String ample=input.nextLine();
System.out.println("Enter the String to be matched here: ");
String mrx=input.nextLine();
if(ample.equals(mrx)){
System.out.println("\nResult: Matched !! Both strings are equal");
}
else{
System.out.println("\nResult: Not Matched !! Both Strings are distinct to each other");
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Java String Method equalsIgnoreCase()

Usando equalsIgnoreCase() , você pode comparar duas strings independentemente de serem minúsculas ou maiúsculas.

Um valor true é retornado se as strings forem iguais, enquanto um valor false é retornado se não forem.

Observação : para comparar duas strings em ordem alfabética, ignore as diferenças de maiúsculas e minúsculas usando o método compareToIgnoreCase().

Sintaxe

public boolean equalsIgnoreCase(String mrx_String)

Parâmetros

mrx_String é outra string a ser comparada com a primeira string, independentemente do caso que tenha.

O exemplo a seguir explica o funcionamento do método equalsIgnoreCase() :

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Main {
public static void main(String[] args) {
String ample="The equalsIgnoreCase() method matches two strings character by character";
String mrx="THE EQUALSIGNORECASE() METHOD MATCHES TWO STRINGS CHARACTER BY CHARACTER";
System.out.println("\nString 1: "+ample);
System.out.println("String 2: "+mrx);
System.out.println("\n--> Does the Two Strings equals each other irrespective of their case: ");
System.out.println("Answer: "+ample.equalsIgnoreCase(mrx));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

O programa abaixo pega duas strings como entrada do usuário e as compara em ordem alfabética, ignorando o caso em que estão escritas:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter the String here: ");
String ample=input.nextLine();
System.out.println("Enter the string to be matched here having any word case: ");
String mrx=input.nextLine();
if(ample.equalsIgnoreCase(mrx)){
System.out.println("\nResult: Matched !! Both strings are equal having different word cases");
}
else{
System.out.println("\nResult: Not Matched !! Both Strings are distinct to each other");
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String hashCode()

Usando o método hashCode() , você pode obter o hashcode da string.

Veja como o código hash de um objeto String é calculado:

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

Nesse caso, s[i] representa o i-ésimo caractere de uma string, n representa seu comprimento e ^ indica exponenciação.

Sintaxe

public int hashCode()

Parâmetros

Um valor inteiro é retornado como uma saída.

Os exemplos a seguir mostram o hashcode da string “Mr.Examples” :

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Main {
public static void main(String[] args) {
String mrx="Mr.Examples";
System.out.println("The Hashcode of the given string is: "+mrx.hashCode());
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

O programa a seguir mostra o cálculo do Hashcode depois de receber a entrada do usuário:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter String here: ");
String mrx=input.nextLine();
System.out.println("\n--> String :"+mrx);
System.out.println("--> Hash Code of the String is: "+mrx.hashCode());
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String isEmpty()

O método isEmpty() verifica a existência de uma string vazia em uma propriedade string.

De acordo com este método, se a string estiver vazia (length() é zero), ela retorna true, caso contrário, retorna false .

Sintaxe

public boolean isEmpty()

O funcionamento do método isEmpty() pode ser explicado seguindo o exemplo abaixo:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Main {
public static void main(String[] args) {
String mrx="";
String ample="Mr.Examples";
System.out.println("\n--> Is String mrx empty ?");
System.out.println("Answer: "+mrx.isEmpty());
System.out.println("\n--> Is String ample empty ?");
System.out.println("Answer: "+ample.isEmpty());
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Da mesma forma, também podemos verificar o método isEmpty() para verificar várias Strings e strings definidas pelo usuário também:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter String here: ");
String mrx_ample=input.next();
String mrx="";
String ample=" ";
System.out.println("\n--> Is String "+mrx_ample+" empty ?");
System.out.println("Answer: "+mrx_ample.isEmpty());
System.out.println("\n--> Is String mrx empty ?");
System.out.println("Answer: "+mrx.isEmpty());
System.out.println("\n--> Is String ample empty ?");
System.out.println("Answer: "+ample.isEmpty()+". This shows that even spaces occupy some length in a string.");
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String indexOf()

Usando indexOf() , você pode encontrar onde a primeira ocorrência do(s) caractere(s) especificado(s) está dentro de uma string.

Conselho: Para encontrar a última ocorrência de um ou mais caracteres especificados em uma string, use o método lastIndexOf() .

Sintaxe

IndexOf() tem quatro métodos:

public int lastIndexOf(String mrx)
public int lastIndexOf(String mrx, int ample_start_index)
public int lastIndexOf(int ample)
public int lastIndexOf(int ample, int mrx_start_index)

Parâmetros

O parâmetro mrx representa a string a ser procurada.

ample_start_search e mrx_start_search são tipos de dados inteiros que representam a posição no índice de onde pode começar a pesquisa. Na ausência desse parâmetro, o comprimento da string é usado.

Um amplo representa um único caractere, como 'A' ou um valor Unicode.

Aqui, encontramos o índice da palavra sobre :

Example: 

1
2
3
4
5
6
7
8
9
10
11
public class Main {
public static void main(String[] args) {
String mrx="Hello Learner !! We are discussing about the IndexOf() method";
System.out.println("The Index of about is: "+mrx.indexOf("about"));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Aqui está um exemplo de como o mesmo trabalho pode ser feito recebendo uma entrada do usuário:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter String here: ");
String ample=input.nextLine();
System.out.println("Enter word whose Index number you want to find: ");
String mrx=input.nextLine();
System.out.println("\nThe Index of "+mrx+" in the string is: "+ample.indexOf(mrx));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

O exemplo abaixo mostra o último índice do caractere d, ao iniciar a pesquisa a partir do índice número 2:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Main {
public static void main(String[] args) {
String mrx="Hello Learner !! We are discussing about the indexOf() method";
System.out.println("The Index of d starting search from 7 is: "+mrx.indexOf('d',2));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String lastIndexOf()

Usando o método lastIndexOf() , você pode descobrir onde determinado(s) caractere(s) apareceu(m) por último em uma string.

Observação : quando o método indexOf() é chamado, ele retorna a primeira ocorrência do(s) caractere(s) especificado(s) de uma string.

Sintaxe

Os quatro métodos a seguir estão disponíveis para lastIndexOf():

public int lastIndexOf(String mrx)
public int lastIndexOf(String mrx, int ample_start_index)
public int lastIndexOf(int ample)
public int lastIndexOf(int ample, int mrx_start_index)

Parâmetros

O parâmetro mrx representa a string a ser procurada.

ample_start_search e mrx_start_search são tipos de dados inteiros que representam a posição no índice de onde pode começar a pesquisa. Na ausência desse parâmetro, o comprimento da string é usado.

Um amplo representa um único caractere, como 'A' ou um valor Unicode.

Aqui, encontramos o último índice da palavra sobre:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Main {
public static void main(String[] args) {
String mrx="Hello Learner !! We are discussing about the LastIndexOf() method";
System.out.println("The Last Index of about is: "+mrx.lastIndexOf("about"));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

O mesmo trabalho poderia ser feito recebendo uma entrada do usuário, conforme mostrado abaixo:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter String here: ");
String ample=input.nextLine();
System.out.println("Enter word whose last Index you want to find: ");
String mrx=input.nextLine();
System.out.println("\nThe last Index of "+mrx+" in the string is: "+ample.lastIndexOf(mrx));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

O exemplo abaixo mostra o Último Índice do caractere e, iniciando a busca a partir do índice número 7:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Main {
public static void main(String[] args) {
String mrx="Hello Learner !! We are discussing about the LastIndexOf() method";
System.out.println("The Last Index of e starting search from 7 is: "+mrx.lastIndexOf('e',7));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Comprimento do método de string Java ()

Usando o método length() , você pode obter o comprimento de qualquer string.

Lembre-se: strings vazias têm comprimento 0.

Sintaxe

public int length()

O exemplo a seguir mostra o comprimento de uma string contendo números de 0 a 9:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Main {
public static void main(String[] args) {
String mrx="0123456789";
System.out.println("The length of the String "+mrx+" is: "+mrx.length());
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Também podemos usar a entrada do usuário para encontrar o comprimento de uma string, conforme mostrado abaixo:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter String here: ");
String mrx=input.nextLine();
System.out.println("\n--> The length of the String { "+mrx+" } is: "+mrx.length());
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String replace()

Usando replace() , você pode substituir uma string por uma nova string contendo o(s) caractere(s) especificado(s) da primeira string.

Sintaxe

public String replace(char mrx_search, char ample_new)

Parâmetros

mrx_search é um caractere que representa o caractere que deve substituir o caractere que está em uso no momento.

Um valor ample_new é especificado como um caractere, indicando o caractere que será usado para substituir o mrx_search.

Para entender melhor o método String replace() , veja o exemplo abaixo:

Example: 

1
2
3
4
5
6
7
8
9
10
11
public class Main {
public static void main(String[] args) {
String mrx="Mr.Examples";
System.out.println(mrx.replace('r','R'));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

O programa a seguir recebe entradas do usuário e substitui os caracteres especificados e exibe a saída de acordo:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter String here: ");
String mrx=input.nextLine();
System.out.println("Enter Character to replace here: ");
String ample_1=input.next();
System.out.println("Enter Character to be replaced here: ");
String ample_2=input.next();
System.out.println("\n——————– O U T P U T ——————————");
System.out.println("\n--> Original String: "+mrx);
System.out.println("--> After Replacing "+ample_1+" with "+ample_2+" we get: "+mrx.replace(ample_1,ample_2));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String toLowerCase()

Usando o método to LowerCase() , pode-se converter uma string de letras maiúsculas para letras minúsculas.

Importante: Strings são convertidas em letras maiúsculas pelo método toUpperCase().

Sintaxe

public String toLowerCase()

O exemplo fornecido irá guiá-lo sobre o funcionamento do método toLowerCase() :

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Main {
public static void main(String[] args) {
String mrx=" THE STRING METHODS MAKE IT EASIER FOR THE USER TO PERFORM DIFFERENT OPERATIONS ON JAVA STRINGS ";
System.out.println("\nCurrent String: "+mrx);
System.out.println("\nAfter Converting to LowerCase: "+mrx.toLowerCase());
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Da mesma forma, podemos fazer a mesma operação na string depois de receber a entrada do usuário. O exemplo dado demonstra o funcionamento:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter String in UpperCase : ");
String mrx=input.nextLine();
String upper_mrx=mrx.toUpperCase();
System.out.println("\n—————————– R E S U L T ———————————");
System.out.println("\n--> Before Changing case :"+upper_mrx);
System.out.println("--> After Changing to Lowercase: "+mrx.toLowerCase());
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String toUpperCase()

Ao chamar toUpperCase() , você pode converter uma string em letras maiúsculas.

Observação: usando o método toLowerCase(), podemos converter uma string em caracteres minúsculos.

Sintaxe

public String toUpperCase()

O exemplo abaixo mostra a conversão de uma String de letras minúsculas para letras maiúsculas:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Main {
public static void main(String[] args) {
String mrx=" the string methods make it easier for the user to perform different operations on java strings ";
System.out.println("\n--> Current String: "+mrx);
System.out.println("\n--> After Converting to UpperCase: "+mrx.toUpperCase());
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Assim, após receber a entrada do usuário, podemos realizar a mesma operação na string. O exemplo a seguir ilustra como funciona:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter String in LowerCase : ");
String mrx=input.nextLine();
String lowerCase_mrx=mrx.toLowerCase();
System.out.println("\n—————————– R E S U L T ———————————");
System.out.println("\n--> Before Changing case : "+lowerCase_mrx);
System.out.println("--> After Changing to Upper Case: "+mrx.toUpperCase());
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Método Java String trim()

No método trim() , os espaços em branco são removidos de ambas as extremidades de uma string.

Importante : A string original não será alterada por este método.

Sintaxe

public String trim()

Aqui está um exemplo de como remover espaços em branco de ambos os lados de uma string:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Main {
public static void main(String[] args) {
String mrx=" Since We have Covered All the methods from String Methods Java.I hope you would have found it easier and interesting. ";
System.out.println("\n--> Original String: "+mrx);
System.out.println("\n--> After Using the trim function: "+mrx.trim());
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Correspondentemente, aqui está outro exemplo para demonstrar o funcionamento do método trim() de uma maneira mais fácil:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Main {
public static void main(String[] args) {
String mrx=" Mr. Examples ";
System.out.println("\n--> Original String: "+mrx);
System.out.println("\n--> After Using the trim function: "+mrx.trim());
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Java Como Contar Palavras

Contar o número de palavras em uma string

O exemplo a seguir pode ser usado para contar facilmente o número de palavras contidas em uma string:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Main {
public static void main(String[] args) {
String mrx="You are learning Java Programming Language";
int count_ample=mrx.split("\\s").length;
System.out.println("There are "+count_ample+" words in the given string");
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Da mesma forma, se você quiser encontrar a contagem de palavras em uma string inserida pelo usuário, consulte o exemplo abaixo:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter the String here : ");
String mrx=input.nextLine();
int count_ample=mrx.split("\\s").length;
System.out.println("\n--> String: "+mrx);
System.out.println("--> Count = There are "+count_ample+" words in the given string");
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Java Como inverter uma string

Você pode reverter facilmente os caracteres de uma string, um por um, seguindo as etapas abaixo:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Main {
public static void main(String[] args) {
String ample = "Hello Learner !! We are Learning how to reverse a String in Java";
String mrx_reversed = "";
for (int i = 0; i < ample.length(); i++) {
mrx_reversed = ample.charAt(i) + mrx_reversed;
}
System.out.println("\n--> Before Reversing String : "+ample);
System.out.println("\n--> Reversed string: "+ mrx_reversed);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Da mesma forma , ao obter uma entrada do usuário, também podemos imprimir a string da maneira invertida , conforme mostrado no exemplo abaixo:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
System.out.println("Enter Any String here: ");
String mrx=input.nextLine();
String ample_reversed="";
for(int looping_element=0;looping_element<mrx.length();looping_element++){
ample_reversed=mrx.charAt(looping_element)+ample_reversed;
}
System.out.println("\n--> User Input Before Reversing: "+mrx);
System.out.println("\n--> After Reversing: "+ample_reversed);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 

Nós valorizamos o seu feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Assine a nossa newsletter
Digite seu e-mail para receber um resumo semanal de nossos melhores posts. Saber mais!
ícone