[POO] aula03 extras added

This commit is contained in:
TiagoRG 2023-03-04 20:26:54 +00:00
parent a6c02e82e0
commit fec773193a
Signed by untrusted user who does not match committer: TiagoRG
GPG Key ID: DFCD48E3F420DB42
3 changed files with 75 additions and 0 deletions

Binary file not shown.

View File

@ -0,0 +1,24 @@
package aula03;
import java.util.Scanner;
import utils.StringMethods;
public class StringExtras {
public static void main(String[] args) {
Scanner sin = new Scanner(System.in);
String str = sin.nextLine();
System.out.println("Frase convertida para minúsculas: " + str.toLowerCase());
System.out.println("Último caracter da frase: " + str.substring(str.length()-1));
System.out.println("Os 3 primeiros caracteres: " + str.substring(0, 3));
System.out.printf("Número de digitos na frase: %d\n", StringMethods.countDigits(str));
System.out.printf("Número de espaços na frase: %d\n", StringMethods.countSpaces(str));
System.out.printf("A frase contém apenas letras minúsculas: %b\n", StringMethods.isAllLower(str));
System.out.println("Frase sem espaços duplicados: " + StringMethods.removeDuplicatedSpaces(str));
System.out.println("A string é um palindromo: " + StringMethods.isPalindrome(str));
System.out.println("Acrónimo da string: " + StringMethods.getAcronym(str));
sin.close();
}
}

View File

@ -0,0 +1,51 @@
package utils;
public class StringMethods {
public static int countDigits(String s) {
int count = 0;
for (char c : s.toCharArray())
if (Character.isDigit(c))
count++;
return count;
}
public static int countSpaces(String s) {
int count = 0;
for (char c : s.toCharArray())
if (c == ' ')
count++;
return count;
}
public static boolean isAllLower(String s) {
for (char c : s.toCharArray())
if (Character.isUpperCase(c))
return false;
return true;
}
public static String removeDuplicatedSpaces(String s) {
StringBuilder newStr = new StringBuilder();
for (char c : s.toCharArray())
if (c != ' ' || !newStr.substring(newStr.length() - 1).equals(" "))
newStr.append(c);
return newStr.toString();
}
public static boolean isPalindrome(String s) {
char[] chars = s.toCharArray();
for (int i = 0; i < s.length() / 2; i++)
if (chars[i] != chars[chars.length - 1 - i])
return false;
return true;
}
public static String getAcronym(String s) {
String[] words = s.split(" ");
StringBuilder acronym = new StringBuilder();
for (String word : words)
if (word.length() >= 3)
acronym.append(word.charAt(0));
return acronym.toString().toUpperCase();
}
}