Replacing string for only one time in Java? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Saying that there are String A = "aabbccdd" and String B = "abcd",
is there any way to remove the matching characters of String B towards String A for only one time?
Expected output is A = "abcd".
I know it will solve the problem when using for loops, but is there any simpler way to do it?
For example, using replaceAll or regular expressions?

you can use distinct() method
public static void main(String[] args) {
String str = "aabbccdd";
String result = str.chars().distinct().boxed()
.map(c -> (char) (c.intValue()))
.map(String::valueOf)
.collect(Collectors.joining());
System.out.println(result);
}

you can use the regex for that
A = A.replaceAll("([a-z]+)\1","");
can find out more about regex here https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

Related

How to convert Stream of Characters into a String in Java 8 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
How to convert Stream<Character> into a String in Java 8? Collectors.joining() expects CharSequence hence it is giving compilation error.
Refer to #jubobs solution link. That is, you could do it this way in your case:
Stream<Character> testStream = Stream.of('a', 'b', 'c');
String result = testStream.collect(Collector.of(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append,
StringBuilder::toString));
This is more performant then map/castping each character to a String first and then joining, as StringBuilder#append(char c) will cut out that intermediate step.
Convert Character to String
Stream<Character> st = Stream.of('C','h','t');
String result = st.map(c->c.toString()).collect(Collectors.joining());
System.out.println(result); //Cht
Or by using method reference
st.map(Object::toString).collect(Collectors.joining())
And Collectors.joining internally uses StringBuilder here
Or just by using forEach
StringBuilder builder = new StringBuilder();
Stream<Character> st = Stream.of('C','h','t');
st.forEach(ch->builder.append(ch));

Regular expression for splitting a String and getting the last part [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to split a String which is a file's name (ex: DIS_LU0786738343_20170608.pdf, KID_AMEV_20170608.pdf, Evolution-DIS_20170512.csv, Offres-invest_20170608.csv, OST_20170608.csv) to get the last part.
For example for the String DIS_LU0786738343_20170608.pdf I want to get only 20170608 which will be transformed on a Date object.
I've been googling this and I found a solution using Regular Expressions:
String regex = "some regex expression";
String fileName = "DIS_LU0786738343_20170608.pdf";
System.out.println(Arrays.toString(fileName.split(regex)));
This will return an Array like this : [DIS_LU0786738343_, 20170608]
So anyone can help me make the Regular Expression to do so ?
String fileName = "DIS_LU0786738343_20170608.pdf";
int startIdx = fileName.lastIndexOf("_");
int endIdx = fileName.lastIndexOf(".");
String finalStr=fileName;
if (startIdx > 0 && endIdx > 0)
finalStr = fileName.substring(startIdx + 1, endIdx);
System.out.println(finalStr);
I think this should work for you.
I dropped down the RegEx thing and found another solution that I want to share with anyone who'll need it in the future :
private LocalDate getDateFromPriipsDoc(File file) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
String fileName = FilenameUtils.getBaseName(file.toString());
String dateInString = fileName.substring(fileName.lastIndexOf("_") + 1);
return LocalDate.parse(dateInString, formatter);
}
Do not hesitate to share another solution with RegEx ;)

How to check if a string contains only specifc characters using regex [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a long string of digits in Java. I want to find of the string contains any one of the digits 0,1,4,6,8,9 or not. I do not want to check if my string contains just any random digits or not.
I don't care how many times the digit is present. If any one of the above digits is present in the string even once, I want to stop right there and return true.
what regex can be used to match this string?
Is there any faster way to do it instead of using regex?
I am using Java 8.
EDIT: I already found lots solutions online for checking if a string contains digits or not. Those solutions don't work here because I want to optimally find out if my string (of length~10^15 characters) contains specific digits or not.
You can use the pattern .*[014689].* along with String.matches():
String input = "1 Hello World";
if (input.matches(".*[014689].*")) {
System.out.println("Match!");
}
Assuming your String is so very big that you have to read it from an InputStream, I'd advise something of the likes :
public static final Pattern TO_MATCH = Pattern.compile("[014689]");
public static boolean hasDigits(InputStream is, int bufferSize){
BufferedReader l_read = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset()),bufferSize);
return l_read.lines().filter(s -> TO_MATCH.matcher(s).find()).findAny().isPresent();
}
Where you can tweak buffersize for performance.
if (preg_match('/[^|]/', $string)) {
// string contains characters other than |
}
or:
if (strlen(str_replace('|', '', $string)) > 0) {
// string contains characters other than |
}

Extract first two characters of a String in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I got a java question which is Given a string, return the string made of its first two chars, so the String "Hello" yields "He".
If the string is shorter than length 2, return whatever there is, so "X" yields "X", and the empty string "" yields the empty string "".
Note that str.length() returns the length of a string.
public String firstTwo(String str) {
if(str.length()<2){
return str;
}
else{
return str.substring(0,2);
}
}
I'm wondering is there any other way can solve this question?
Your code looks great! If you wanted to make it shorter you could use the ternary operator:
public String firstTwo(String str) {
return str.length() < 2 ? str : str.substring(0, 2);
}

Regex help in java validations [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi i want to do some validations.I used to put regex in JS but im new to regex in java, so i tried to make up a code on similar lines in java.
Here is what i did.
1)Check whether first character in string is alphanumeric.
2)Check whether the string atleast 1 number.
so i wrote a code, but it is always returning false.I am not sure if i'm doing this correctly.
private static boolean checkEmbeddedPassword(final String field) {
boolean returnValue=true;
String testpatternAlpha="/^[A-Za-z0-9].+$/";
String testNumber="/[0-9]/";
Pattern pattern=Pattern.compile(testpatternAlpha);
Pattern pattern2=Pattern.compile(testNumber);
Matcher matcher = pattern.matcher(field);
Matcher matcher2 = pattern2.matcher(field);
boolean firstChar=matcher.matches();
boolean numberFlag=matcher2.matches();
System.out.println("-----the value of pwd iss-----"+field);
System.out.println("---------Regex---------Out--put-----"+firstChar);
System.out.println("---------Regex---------Out- for numeral-put-----"+numberFlag);
if(firstChar){
returnValue=false;
}
else if(field.contains(" "))
{
System.out.println("-----------cannot have space------");
returnValue=false;
}
else if(numberFlag)
{
returnValue=false;
}
return returnValue;
}
You don't need the / prefix and suffix in Java:
String testpatternAlpha="^[A-Za-z0-9].+$";
Also in your situation you'll want to be using Matcher.find rather than Matcher.matches. You can read why in the API documentation: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Matcher.html
we do not use / on the beginning and end of the regex in java.
try this...
String testpatternAlpha="^[A-Za-z0-9].+$"; // first character in string is alphanumeric
String testNumber="[0-9]"; //test single number

Categories