This question already has answers here:
How to get position of the first letter in a string [closed]
(3 answers)
Closed 3 years ago.
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*
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;
}
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*
Related
I have a number like this:
1234567890123
and want to format it for example like this
12 34567 89012 3
or maybe like this
1-234 567-890 1 23
How can I achive that? I tried this
DecimalFormat decimalFormat = new DecimalFormat("00 00000 00000 0");
System.out.println(decimalFormat.format(1234567890123L));
But this doesn't work.
I need a way to specify a pattern that can contain any separator character.
import java.text.ParseException;
import javax.swing.text.MaskFormatter;
import org.junit.jupiter.api.Test;
public class FormatTest {
#Test
void testNumberFormat() throws ParseException {
final String format = "#-### ###-### # ##";
final String number = "1234567890123";
MaskFormatter maskFormatter = new MaskFormatter(format);
maskFormatter.setValueContainsLiteralCharacters(false);
System.out.println(maskFormatter.valueToString(number));
}
}
That is not possible with DecimalFormatter and NumberFormatter. But you can use a trick with String and regular expression:
Long.toString(number)
.replaceAll("(\\d{2})(\\d{5})(\\d{5})(\\d)", "$1 $2 $3 $4");
If your format is dynamic, you could do something like this:
#Test
void simon() {
final var input = 1234567890123L;
assertEquals("12 34567 89012 3", formatMyNumber(input, "{2} {5} {5} {1}"));
assertEquals("12-34567-89012-3", formatMyNumber(input, "{2}-{5}-{5}-{1}"));
assertEquals("12_34567_89012_3", formatMyNumber(input, "{2}_{5}_{5}_{1}"));
assertEquals("1 23456 7", formatMyNumber(1234567, "{1} {5} {1}"));
assertEquals("1 2345 6", formatMyNumber(123456, "{1} {4} {1}"));
assertEquals("123.45.6", formatMyNumber(123456, "{3}.{2}.{1}"));
}
private String formatMyNumber(final long number, final String format) {
return Long.toString(number).replaceAll(createRegEx(format), createReplacement(format));
}
private String createRegEx(final String format) {
final var separator = getSeparator(format);
return format.replaceAll("\\{", "(\\\\d{")
.replaceAll("}" + Pattern.quote(separator), "}\\)")
.replaceAll("}$", "}\\)"); // could be integrated in above regex
}
private String getSeparator(final String format) {
final var begin = format.indexOf("}");
final var end = format.indexOf("{", begin);
return format.substring(begin + 1, end);
}
private String createReplacement(final String format) {
final var separator = getSeparator(format);
var replacement = format.replaceAll("^\\{\\d", "\\$X")
.replaceAll("}" + Pattern.quote(separator) + "\\{\\d", separator + "\\$X")
.replaceAll("}$", "");
var counter = 1;
while (replacement.contains("X")) {
replacement = replacement.replaceFirst("X", Integer.toString(counter++));
}
return replacement;
}
It's not my best piece of work but works with dynamic format strings.
Here's something to get you started. Feel free to modify the code to meet your needs.
public class ArbitraryFormat {
public static void main(String[] args) {
ArbitraryFormat arbitraryFormat = new ArbitraryFormat("00 00000 00000 0");
System.out.println(arbitraryFormat.format(1234567890123L));
System.out.println(arbitraryFormat.format(123));
}
private int zeroCount;
private String formatter;
public ArbitraryFormat(String formatter) {
this.formatter = formatter;
this.zeroCount = countZeros(formatter);
}
public String format(long value) {
String tempFormatter = "%" + zeroCount + "s";
String temp = String.format(tempFormatter, value);
StringBuilder builder = new StringBuilder();
int tempIndex = 0;
for (int index = 0; index < formatter.length(); index++) {
if (formatter.charAt(index) == '0') {
builder.append(temp.charAt(tempIndex++));
} else {
builder.append(formatter.charAt(index));
}
}
return builder.toString();
}
private int countZeros(String formatter) {
int count = 0;
int index = 0;
while (index < formatter.length()) {
int pos = formatter.indexOf('0', index);
if (pos >= 0) {
count++;
index = pos + 1;
} else {
index = formatter.length();
}
}
return count;
}
}
You can define your own formatter like this.
public class MyFormat extends NumberFormat {
final String format;
public MyFormat(String format) {
this.format = format;
}
#Override
public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) {
throw new UnsupportedOperationException();
}
#Override
public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) {
toAppendTo.append(number);
for (int i = toAppendTo.length() - 1, j = format.length() - 1; i >= 0 && j >= 0; --i, --j) {
char fch = format.charAt(j);
if (fch != '*') {
toAppendTo.insert(i + 1, fch);
--j;
}
}
return toAppendTo;
}
#Override
public java.lang.Number parse(String source, ParsePosition parsePosition) {
throw new UnsupportedOperationException();
}
}
And
public static void main(String[] args) throws ParseException {
long number = 1234567890123L;
MyFormat mf1 = new MyFormat("* ***** ***** *");
MyFormat mf2 = new MyFormat("*-*** ***-*** * **");
System.out.println(mf1.format(number));
System.out.println(mf2.format(number));
}
output:
12 34567 89012 3
1-234 567-890 1 23
Thanks to #McPringle I finally implemented this solution:
public class MaskFormatter {
private char[] separators;
public String formatNumber(Number number, String pattern) {
if (number == null) {
return "";
} else {
separators = pattern.replace("0", "").toCharArray();
String string = number.toString();
String regex = createRegex(pattern);
String replacement = createReplacement(pattern);
return string.replaceAll(regex, replacement);
}
}
private String createRegex(String pattern) {
String[] parts = pattern.split("[" + createPatternFromSeparators() + "]");
StringBuilder sb = new StringBuilder();
for (String part : parts) {
sb.append("(\\d{").append(part.length()).append("})");
}
return sb.toString();
}
private String createReplacement(String pattern) {
String[] parts = pattern.split("[" + createPatternFromSeparators() + "]");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
if (i > 0) {
char separator = separators[i - 1];
sb.append(separator);
}
sb.append("$").append(i + 1);
}
return sb.toString();
}
private String createPatternFromSeparators() {
Set<String> set = new HashSet<>();
for (char separator : separators) {
set.add(String.valueOf(separator));
}
return String.join("", set);
}
}
You can also use String.replaceAll(). Like the following example.
long value = 1234567890123L;
String str = String.valueOf(value);
//12 34567 89012 3
String str1 = str.replaceAll("^(.{2})(.{5})(.{5})(.{1})$", "$1 $2 $3 $4");
System.out.println(str1); //Prints: 12 34567 89012 3
//1-234 567-890 1 23
String str2 = str.replaceAll("^(.{1})(.{3})(.{3})(.{3})(.{1})(.{2})$", "$1-$2 $3-$4 $5 $6");
System.out.println(str2); //Prints: 1-234 567-890 1 23
I'm trying to pick out the characters of a string that come just before and just after the part of the string that matches another string, creating a completely different string. I.e. when the method wordEnds(String str, String word) is called, and str = "XY1XY" and word = "XY", then the new string would be "11".
Here is what I have so far:
package codingBat;
public class CodingBat {
public static String wordEnds(String str, String
word) {
String newStr = null;
if(str.equals(word)) {
return "";
}
else if(!str.contains(word)) {
return "";
}
else {
for(int i = 0;i < str.length();i++) {
if((word.equals(str.substring(i,i+1)))){
newStr = newStr + (str.substring(i-1,i+2));
}
else {
return newStr;
}
}
return newStr;
}
}
}
Try to use regex, pattern for your example ll look like this XY.*XY. But You have to change the XYto the string parameter so it ll be pattern = str+"(.*)"+str. Then you can use the group and read the string from middle
Here is a code:
static String middleString(String str, String word) {
Pattern pattern = Pattern.compile(str + "(.*)" + str);
Matcher matcher = pattern.matcher(word);
matcher.matches();
return matcher.group(1);
}
This call:
System.out.println(middleString("XY", "XY11XY"));
Returns 11
I need to test a method that takes an input TextFild, how can I change the input to ArrayList to get the data. I am getting an error that says
java.lang.ClassCastException: class java.lang.Character cannot be cast to class
private boolean validatePassword() {
Pattern p = Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,15})");
Matcher matcher = p.matcher(passwordField.getText());
if (matcher.matches()) {
return true;
} else {
lblMessage.setText("Please enter a valid password \n" +
"(at least one uppercase, lowercase and 8 or more characters ");
return false;
}
}
my solution
public class TestCases {
ArrayList<Character> characters = new ArrayList<>();
public boolean validatePassword() {
Pattern p = Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,15})");
for (int i = 0; i < characters.size(); i++) {
Object j = characters.get(i);
Matcher matcher = p.matcher((CharSequence) j);
if (matcher.matches()) {
return true;
} else {
System.out.println(
"Please enter a valid password \n" +
"(at least one uppercase, lowercase and 8 or more characters "););
return false;
}
}
return false;
}
public void setEmail(ArrayList<Character> list) {
characters = list;
}
}
Junit class
#Test
void test() {
String password= "Kd123456";
ArrayList<Character> paswordField=new ArrayList<>();
for(int i= 0 ; i<password.length(); i++){
paswordField.add(password.charAt(i));
}
TestCases valid= new TestCases();
valid.setEmail(paswordField);
assertEquals(true,valid.validatePassword());
}
}
if hope this will help you !!
import static org.junit.Assert.assertEquals;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
public class TestCases {
public boolean validatePassword(String s) {
Pattern p = Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-z0-9 ]).{8,15})",
Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(s);
if (matcher.matches()) {
return true;
} else {
System.out.println("Please enter a valid password \n"
+ "(at least one uppercase, lowercase and 8 or more characters ");
return false;
}
}
#Test
public void test() {
String password = "Kd12#3456";
TestCases valid = new TestCases();
assertEquals(true, valid.validatePassword(password));
}
}
Is there something I am doing wrong here? When printed I get "*" and I need to get "-32". I am parsing each individual word and returning the last word.
public static void main(String[] args) {
System.out.println(stringParse("3 - 5 * 2 / -32"));
}
public static String stringParse(String string) {
String[] word = new String[countWords(string)];
string = string + " ";
for (int i = 0; i <= countWords(string); i++) {
int space = string.indexOf(" ");
word[i] = string.substring(0, space);
string = string.substring(space+1);
}
return word[countWords(string)];
}
public static int countWords(String string) {
int wordCount = 0;
if (string.length() != 0) {
wordCount = 1;
}
for (int i = 0; i <= string.length()-1; i++){
if (string.substring(i,i+1).equals(" ")) {
wordCount++;
}
}
return wordCount;
}
You could instead split the string by white space using "\\s+" and return the last element of that array. This will return the last word.
public static String stringParse(String s){
return s.split("\\s+")[s.split("\\s+").length-1];
}
In this case you can use regular expressions too :
public static void main(String[] args) {
System.out.println(stringParse("3 - 5 * 2 / -32"));
}
public static String stringParse(String string) {
String found = null;
Matcher m = Pattern.compile("\\s((\\W?)\\w+)$", Pattern.CASE_INSENSITIVE)
.matcher(string);
while (m.find()) {found = m.group();}
return found;
}
Using a for loop, how do I go about making all consonants in a string uppercase?
I think I should do something like this:
String str = "fish$"
String strConsonants = "f, s, h";
for (int x = 0; x < str.length(); x++)
{
if(((str.charAt(x) == (strConsonants))
{
System.out.print("FiSH$");
}
}
use String.contains() method from String API. the followingcode would work for your present input. usually, if you want to find all the consonents, have an char[] of consonents or String with all the consonents and do the check.
String str = "fish$";
String strConsonants = "f, s, h";
String temp="";
for (int x = 0; x < str.length(); x++){
temp+= str.charAt(x);
if(!strConsonants.contains(temp)) {
consonentsUCase+=temp.toUpperCase();
}
temp="";
}
I've just written it.
Output: FiSH$
Works for any word ! ;)
API method: printStringWithUpperConsonant
import java.util.HashSet;
import java.util.Set;
public class ConsonantUtils {
private Set<Character> vowels = getVowels();
private String analysedString;
public ConsonantUtils(String analysedString) {
this.analysedString = analysedString;
}
public static void main(String[] args) {
new ConsonantUtils("fish$").printStringWithUpperConsonant();
}
public void printStringWithUpperConsonant() {
for (int i = 0; i < getAnalysedString().length(); i++) {
printChar(getCurrentChar(i));
}
}
private char getCurrentChar(int i) {
return getAnalysedString().charAt(i);
}
private void printChar(char currentChar) {
if (isConsonant(currentChar)) {
System.out.print(makeCharUpperCase(currentChar));
}
else{
System.out.print(currentChar);
}
}
private Set<Character> getVowels() {
Set<Character> vowels = new HashSet<Character>();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
return vowels;
}
private char makeCharUpperCase(char character) {
return Character.toUpperCase(character);
}
private boolean isConsonant(char currentChar) {
return !vowels.contains(currentChar);
}
private String getAnalysedString(){
return analysedString;
}
}
You can use Character.toUpperCase().
String vowels = "aeiouAEIOU";
char[] charArr = str.toCharArray(); //turn the string into char array
for(int i=0; i<charArr.length; i++) { //for loop
if(vowels.indexOf(charArr[i]) == -1) { // if not a vowel
charArr[i] = Character.toUpperCase(charArr[i]); //replace with upper case
}
}
Sting rslt = String.valueOf(charArr); //finally turn the array back to string
String str = "fish$";
String strVowels = "aeiouAEIOU";
String out = "";
for (Character c : str.toCharArray())
{
if(!strVowels.contains(""+c))
{
out = out + Character.toUpperCase(c);
}
else
{
out = out + c;
}
}
System.out.println(out);
This works for me:
List<Character> constants = Arrays.asList('f', 's', 'h');
String str = "fish$";
for (Character c : constants) {
str = str.replace(c, Character.toUpperCase(c));
}