Browse array and replace

1

I have this exercise, but I could not advance almost.

Return a new string with the initial letter in upper case and the rest of the letters replace with points.

If the string is "", return a string with a period.

Example:

String1("") → "."
String1("carlos") → "C...."

This is the code I have:

public String myString1(String str) 
{
 if (str == null || str.isEmpty()) {
    return str;            
  } else {
    return  Character.toUpperCase(str.charAt(0)) + str.substring(1, str.length()).toLowerCase();
  }
}
    
asked by Juan 17.10.2018 в 23:44
source

2 answers

0

The first part that is to convert the first character in upper case you already have it done, you can comment on an array but you can also get the following characters and replace them with "." in this way:

public static String myString1(String str) {
 if(str == null){
  return "";
 }else if (str.isEmpty()) { //String vacio retorna "."
   return ".";            
 } else {
     //Convierte primer caracter en mayuscula.
     String firstLetter = String.valueOf(Character.toUpperCase(str.charAt(0)));
     //Convierte siguientes caracteres a "."
     String otherLetters = str.substring(1, str.length()).toLowerCase();     
     nextLetters = otherLetters.replaceAll("[^\d.]", ".");
     //Retorna resultado
     return firstLetter + nextLetters;
  }
}

Usage examples:

1)

System.out.println("Resultado: " + myString1("carlos"));

would have an exit:

Resultado: C.....

2)

System.out.println("Resultado: " + myString1(""));

would have an exit:

Resultado: .
    
answered by 17.10.2018 в 23:52
0

The truth is not so bad, you just need to replace the rest of characters with points.
In Java 8 you can use Collections.nCopies with String.join of the form String.join("", Collections.nCopies(n, str)) where Collections.nCopies(n, str) creates a List object with the object str repeated n times.
and to meet what you need str must be the point and n the length of String -1.

public static void main(String[] args) throws Exception {
    List<String> lista = new LinkedList();
    lista.add("carlos");
    lista.add("c");
    lista.add("");
    lista.add(null);
    for(String data : lista){
        System.out.println(myString1(data));
    }
}
/**
 * si String viene vacio se devuelve un punto  
 * de lo contrario coloca la primera letra en Mayuscula y el resto con puntos
 * @param str
 * @return 
 */
public static String myString1(String str) {
    String dot = ".";
    if (str == null || str.isEmpty()) {
        return dot;            
    } else {
        return  Character.toUpperCase(str.charAt(0)) + String.join("", Collections.nCopies(str.length()-1, dot));
    }
}

If you execute it, it will come out:

C.....
C
.
.

If for some reason you use Java 11 , the replay part is easier with repeat :

str.repeat(n);

Of these forms you avoid that a strange character is entered and even be replaced by a point

    
answered by 18.10.2018 в 16:59