0
public String setPassword(String username) {
    int passl = 8;
    String s = username;
    if(s.length()<passl) {
        s+="*";
    }
    if(s.length()>passl) {
            s=s.substring(0,passl);
    }

    return s.replaceAll( "[aeiou]", "*" );
}

I have this code. When it gets a username it replaces all vowels to * and now I need to replace first found alphabetic char to uppercase char. Like username is AdrianDe and it must return something like this *Dr**nD*

I1yStery
  • 3
  • 1

2 Answers2

1

You can do it as follows:

public class New {
    public static void main(String[] args) {
        String username="AdrianDe";
        System.out.println(setPassword(username));
        System.out.println(firstLetterCap(setPassword(username)));
    }
    static String setPassword(String username) {
        int passl = 8;
        String s = username;
        if(s.length()<passl) {
            s+="*";
        }
        if(s.length()>passl) {
                s=s.substring(0,passl);
        }

        return s.replaceAll( "[AEIOUaeiou]", "*" );
    }
    static String firstLetterCap(String s) {
        int i;
        StringBuffer sb=new StringBuffer();
        for (i = 0; i < s.length(); i++) {
            if (Character.isLetter(s.charAt(i)))               
                break;  
            sb.append(s.charAt(i));
        }
        sb.append((char)(s.charAt(i)-32));
        sb.append(s.substring(i+1,s.length()));
        return sb.toString();
    }   
}

Output:

*dr**nD*
*Dr**nD*
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

Here is the missing part:

   String result = s.replaceAll("(?i)[aeiou]", "*");   // (?i) for case insensitive
   Pattern pattern = Pattern.compile("([a-zA-Z])");  // any character
   Matcher matcher = pattern.matcher(result);
   if(matcher.find()){
      result = matcher.replaceFirst(matcher.group(0).toUpperCase()); 
   }

Full method:

    public String setPassword(String username) {
        int passl = 8;
        String s = username;
        if (s.length() < passl) {
            s += "*";
        }
        if (s.length() > passl) {
            s = s.substring(0, passl);
        }

        s = s.replaceAll("(?i)[aeiou]", "*");   // (?i) for case insensitive
        Pattern pattern = Pattern.compile("([a-zA-Z])");  // any character
        Matcher matcher = pattern.matcher(s);
        if (matcher.find()) {
            s = matcher.replaceFirst(matcher.group(0).toUpperCase());
        }

        return s;
    }
Petr Aleksandrov
  • 1,434
  • 9
  • 24