Search and get equal characters in a String - java

I need to search for a certain String in another character-by-character string and if the characters are the same get such a character;
I'm doing it this way
public String searchForSignature(String texto2) throws NoSuchAlgorithmException {
String myString = "", foundString = "";
myString = "aeiousrtmvb257";
for (int i = 0; i < texto2.length() || i <= 1000; i++) {
char c = texto2.charAt(i);
for (int j = 0; j < myString.length(); j++) {
if (c == myString.charAt(j)) {
foundString = foundString + c;
}
}
}
return foundString;
}
I would like to improve the performance and saw that there are forms and using regular expressions, as I am still a little lay I could not succeed in the way I did.
public String searchForSignature2(String texto2) {
Pattern pattern = Pattern.compile("aeiousrtmvb257");
Matcher matcher = pattern.matcher(texto2);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
return matcher.group(1).toString();
}
Does not return anything
//edit
Really, I guess I was not very clear on the question.
Actually I need to get all the characters equal to "aeiousrtmvb257" the ones that are in the String
I did it that way, now it seems OK, I just do not know if the performance is satisfactory.
public String searchForSignature2(String texto2) {
String foundString = "";
Pattern pattern = Pattern.compile("[aeiousrtmvb257]");
Matcher matcher = pattern.matcher(texto2);
while (matcher.find()) {
System.out.println(matcher.group());
foundString+=matcher.group();
}
return foundString;
}
}

As far as I understood your question, by using Patternand Matcher this should do the trick:
Code
private static final String PATTERN_TO_FIND = "[aeiousrtmvb257]";
public static void main(String[] args) {
System.out.println(searchForSignature2("111aeiousrtmvb257111"));
}
public static String searchForSignature2(String texto2) {
Pattern pattern = Pattern.compile(PATTERN_TO_FIND);
Matcher matcher = pattern.matcher(texto2);
StringBuilder result = new StringBuilder();
while (matcher.find()) {
result.append(matcher.group());
}
return result.toString();
}
Output
aeiousrtmvb257

I don't know what was the reason behind texto2.length() || i <= 1000, but based on the logic in your method, I could suggest the below solution:
public static void main(String... args) throws IOException {
System.out.println(searchForSignature("hello"));
}
public static String searchForSignature(String texto2) {
String myString = "aeiousrtmvb257";
StringBuilder builder = new StringBuilder();
for (char s : texto2.toCharArray()) {
if (myString.indexOf(s) != -1) {
builder.append(s);
}
}
return builder.toString();
}
Output: eo

I don't get it, why would you print the string that you found
public static String searchForSignature2(String texto2) {
String maaString = "aeiousrtmvb257";
String toSearch = ".*" + maaString +".*";
boolean b = Pattern.matches(toSearch, texto2);
return b ? maaString : "";
}
public static void main(String[] args)
{
String input = "4erdhrAW BLBAJJINJOI WETSEKMsef saemfosnens3bntu is5o3n029j29i30kwq23eki4"+
"maoifmakakmkakmsmfajiwfuanyi gaeniygaenigaenigeanige anigeanjeagjnageunega"+
"movmmklmklzvxmkxzcvmoifsadoi asfugufngs"+
"wpawfmaopfwamopfwampfwampofwampfawmfwamokfesomk"+
"3rwq3rqrq3rqetgwtgwaeiousrtmvb2576266wdgdgdgdgd";
String myString = searchForSignature2(input);
System.out.println(myString);
}
you need to add .* to tell that your string is surrounded by any char

Related

regex email validation

this is a continuation of my earlier post, My code:
public class Main {
static String theFile = "C:\\Users\\Pc\\Desktop\\textfile.txt";
public static boolean validate(String input) {
boolean status = false;
String REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
status = true;
} else {
status = false;
}
return status;
}
public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(theFile));
String line;
int count = 0;
while ((line = br.readLine()) != null) {
String[] arr = line.split("#");
for (int x = 0; x < arr.length; x++) {
if (arr[x].equals(validate(theFile))) {
count++;
}
System.out.println("no of matches " + count);
}
}
} catch (IOException e) {
e.printStackTrace();
}
Main.validate(theFile);
}
}
It shows result :
no of matches 0
no of matches 0
no of matches 0
no of matches 0
and this is my text in input file
sjbfbhbs#yahoo.com # fgfgfgf#yahoo.com # ghghgh#gamil.com #fhfbs#y.com
my output should be three emails because the last string is not a standard email format
I know I'm not suppose to pass (arr[x].validate(theFile)))
I have always used this:
public static bool Validate(string email)
{
string expressions = #"^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$";
return Regex.IsMatch(email, expressions);
}
Note: I also have a function that "cleans" the string should there be multiple # symbols also.
Edit: Here is how I clean out extra # symbols. Note this will keep the FIRST # it finds and just remove the rest. This function should be used BEFORE you run the validation function on it.
public static string CleanEmail(string input)
{
string output = "";
try
{
if (input.Length > 0)
{
string first_pass = Regex.Replace(input, #"[^\w\.#-]", "");
List<string> second_pass = new List<string>();
string third_pass = first_pass;
string final_pass = "";
if (first_pass.Contains("#"))
{
second_pass = first_pass.Split('#').ToList();
if (second_pass.Count >= 2)
{
string second_pass_0 = second_pass[0];
string second_pass_1 = second_pass[1];
third_pass = second_pass_0 + "#" + second_pass_1;
second_pass.Remove(second_pass_0);
second_pass.Remove(second_pass_1);
}
}
if (second_pass.Count > 0)
{
final_pass = third_pass + string.Join("", second_pass.ToArray());
}
else
{
final_pass = third_pass;
}
output = final_pass;
}
}
catch (Exception Ex)
{
}
return output;
}
There are several errors in your code:
if (arr[x].equals(validate(theFile))) checks whether the mail address string equals the boolean value you get from the validate() method. This will never be the case.
In the validate() method, if you only want to check if the string matches a regex, you can simply do that with string.matches(pattern) - so you only need one line of code (not really in error, but it's more elegant this way)
After splitting your input string (the line), there are whitespaces left, because you only split at the # symbol. You can either trim() each string afterwards to remove those (see the code below) or split() at \\s*#\\s* instead of just #
Here is an example with all the fixes (i left out the part where you read the file and used a string with your mail addresses instead!):
public class Main {
private static final String PATTERN_MAIL
= "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
public static boolean validate(String input) {
return input.matches(PATTERN_MAIL);
}
public static void main(String[] args) {
String line = "sjbfbhbs#yahoo.com # fgfgfgf#yahoo.com # ghghgh#gamil.com #fhfbs#y.com";
String[] arr = line.split("#");
int count = 0;
for (int x = 0; x < arr.length; x++) {
if (validate(arr[x].trim())) {
count++;
}
System.out.println("no of matches " + count);
}
}
}
It prints:
no of matches 1
no of matches 2
no of matches 3
no of matches 4
EDIT: If the pattern is not supposed to match the last mail address, you'll have to change the pattern. Right now it matches all of them.

How to use regular expressions in the output +-12aba to +-12

How to use regular expressions in the output +-12aba to +-12, that is, except to a digital and minus symbol so far.
public class LeetCode8 {
public static int myAtoi(String str) {
str = str.replaceAll("\\s+", "");
System.out.println(str);
if (!str.matches("[0-9]+")&&!str.matches("\\+[0-9]+")&&!str.matches("\\-[0-9]+")) {
return 0;
}
str.replaceAll("", "0");
if (str.length() > 10) {
return 0;
}
long a = Long.valueOf(str);
if (a > Integer.MAX_VALUE) {
return 0;
}
return (int) a;
}
public static void main(String[] args) {
int i = myAtoi("-12aba");
System.out.println(i);
//i want wo output -12
}
}
Maybe try this:
private int myAtoi(String input){
Pattern p = Pattern.compile("(\\-|\\+)\\d+");
Matcher m = p.matcher(input);
if (!m.find())
return 0;
else
return Integer.valueOf(m.group());
}

Split a string in java containing html

I have a dynamically generated string like :
String s = <span><input style='font-weight:bold'>Hello team</input></span>
I want to split the string as:
String startTag = <span><input style='font-weight:bold'>
String endTag = </input></span>
String content = Hello Team
The String s can be anything (depending on the code) like
<span style='font-weight:bold'>Hello team</span>
or
<td><input style='font-weight:bold'>Hello team</input></td>
So, I want to split based on the index of '>' and '<'?
How can I achieve that?
You can also try to use a SAX Parser.
Implement your own DefaultHandler and override the following methods :
public void characters(char[] ch, int start, int length)
public void startElement (String uri, String localName,
String qName, Attributes attributes)
public void endElement (String uri, String localName, String qName)
If you need help, look this example : https://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html
Good luck
public class Program{
public static void main(String[] args) {
String s = "<span><input style='font-weight:bold'>Hello team</input></span>";
String sCheck = s;
int j=0;
int k=0;
String startTag="";
String storedStartTag="";
String endTag;
String storedEndTag="";
boolean foundEnd=false;
if(s.charAt(0) == '<'){
for (int i = 0;i<sCheck.length();i++){
if(sCheck.charAt(i) == '>'){
j=i;
startTag = sCheck.substring(0,j+1);
storedStartTag = storedStartTag + startTag;
sCheck = sCheck.substring(j+1,sCheck.length());
}
}
}
for (int i = 0;i<s.length();i++){
if(s.charAt(i) == '<'){
if(s.charAt(i+1) == '/'){
k=i;
foundEnd = true;
}
}
if (foundEnd == true){
if(s.charAt(i) == '>'){
endTag = s.substring(k,i+1);
storedEndTag = storedEndTag + endTag;
}
}
}
System.out.println(storedStartTag);
System.out.println(storedEndTag);
}}
This is without Regex, just tried to solve it, don't judge :))
I used the below and it works fine for me. Thanks for the help! :)
int i2 = s.indexOf(">");
int count = 0;
LinkedList<Integer> indexes = new LinkedList<Integer>();
while (i2 >= 0) {
indexes.add(i2);
i2 = s.indexOf(">", i2 + 1);
count ++;
}
int i1 = s.indexOf("</");
int c = count/2;
int b = indexes.get(c-1);
String startTag = s.substring(0,b+1);
String content = s.substring(b+1,i1);
String endTag = s.substring(i1);
public static void main(String[] args) {
String s = "<td><span><td><input style='font-weight:bold'>Hello team</input></td></span></td>";
Pattern p = Pattern.compile("^(<.+>)([a-z A-Z ]+?)(</.+>)$");
Matcher m = p.matcher(s);
if(m.matches()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
System.out.println(m.group(3));
}
}
This, is gonna work, m.group(0) is the hole string so don't use it
It uses regex : regular expression to catch normalized sentences , you find lots of example on the web, lots of programation languages have their proper rules for regex be careful
Use this (single line) to split:
String[] parts = s.split("(?<=>)(?=((?!<[^/]).)*$)|(?=</)", 3);
This splits the input into an array of size 3:
parts[0] // opening tag(s)
parts[1] // content
parts[2] // closing tag(s)
It works for any number of wrapping tags.

Using StringBuilder getting null as output

I am doing one coding question in which I try to decrypt the input string. The procedure for the decryption is:
from 0 to 9 it represent alphabets from a to i.
then 10# represent j, 11# represent k and so.
import java.util.HashMap;
public class Julia {
public static void main(String[] args) {
String s="10#21#12#91";
Julia obj=new Julia();
String result=obj.decrypt(s);
System.out.println(result);
}
public String decrypt(String msg)
{
HashMap<String,Character> hs=new HashMap<>();
hs.put("1",'a');
hs.put("2",'b');
hs.put("3",'c');
hs.put("4",'d');
hs.put("5",'e');
hs.put("6",'f');
hs.put("7",'g');
hs.put("8",'h');
hs.put("9",'i');
hs.put("10",'j');
hs.put("11",'k');
hs.put("12",'l');
hs.put("13",'m');
hs.put("14",'n');
hs.put("15",'o');
hs.put("16",'p');
hs.put("17",'q');
hs.put("18",'r');
hs.put("19",'s');
hs.put("20",'t');
hs.put("21",'u');
hs.put("22",'v');
hs.put("23",'w');
hs.put("24",'x');
hs.put("25",'y');
hs.put("26",'x');
StringBuilder n=new StringBuilder();
for(int i=msg.length()-1;i>=0;i--)
{
if(msg.charAt(i)=='#' && i>=2)
{
StringBuilder s=new StringBuilder().append(msg.charAt(i-2)).append(msg.charAt(i-1));
System.out.println(s);
n.append(hs.get(s));
System.out.println(n);
i=i-2;
}
else
{
n.append(hs.get(msg.charAt(i)));
}
}
return n.toString();
}
}
That is code I wrote. But the output I am getting is nullnullnullnullnull.
I think the issue is with StringBuilder. Can anyone help me with that and explain the concept? If someone has better solution please guide.
You should not use data (a map) when you could have used a simple formula.
My suggestion:
import java.util.ArrayList;
import java.util.List;
public final class Julia {
public static void main(final String[] args) {
final String s = "10#21#12#91";
final String result = decrypt(s);
System.out.println(result);
}
private static String decrypt(final String s) {
final List<Integer> crypt = new ArrayList<>();
final String[] groups = s.split("#");
for (int i = 0; i < groups.length; i++) {
final String group = groups[i];
int j = 0;
// Special case for last group
if ((i == (groups.length - 1)) && !s.endsWith("#")) {
j = group.length();
}
if (group.length() > 2) {
j = group.length() - 2;
}
for (int k = 0; k < j; k++) {
crypt.add(Integer.valueOf(group.substring(k, k + 1)));
}
if (j < group.length()) {
crypt.add(Integer.valueOf(group.substring(j, group.length())));
}
}
final StringBuilder n = new StringBuilder(crypt.size());
for (final Integer c : crypt) {
final char d = (char) (('a' + c) - 1);
n.append(d);
}
return n.toString();
}
}
Please note that there are two mistakes in the question: The letter a is 1, not zero, and the value for 26 is z, not x. The latter error is typical when you use data where a formula would do.
Since you are learning, I would note that the decrypt methods - both my suggestion and yours - should be static since they do not use any fields, so the instantiation is not necessary.
This is Pattern Matching problem which can be solved by Regex.
Your code has some bugs and those are already pointed out by others. I don't see any solution which looks better than a simple regex solution.
Below regex code will output 'julia' for input '10#21#12#91'.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Julia {
public static void main(String[] args) {
String s="10#21#12#91";
Julia obj=new Julia();
String result=obj.decrypt(s);
System.out.println(result);
}
public String decrypt(String msg)
{
Pattern regex = Pattern.compile("((\\d\\d#)|(\\d))");
Matcher regexMatcher = regex.matcher(msg);
StringBuffer result = new StringBuffer();
while (regexMatcher.find())
regexMatcher.appendReplacement(result, getCharForNumber(Integer.parseInt(regexMatcher.group(1).replace("#",""))));
return result.toString();
}
private String getCharForNumber(int i) {
return i > 0 && i < 27 ? String.valueOf((char)(i + 96)) : null;
}
}
I hope it helps.
hs.get(s) will always return null, since s is not a String.
Try hs.get(s.toString())
hs.get(msg.charAt(i)) will also always return null, since you are passing a char to get instead of String.
There may also be logic problems in your code, but it's hard to tell.
Optimized version of your code
public class Main {
public static void main(String[] args) {
String cipher = "10#21#12#91";
System.out.print(decrypt(cipher));
//output : julia
}
static String decrypt(String cipher) {
//split with # to obtain array of code in string array
String[] cipher_char_codes = cipher.split("#");
//create empty message
StringBuilder message = new StringBuilder();
//loop for each code
for (String code : cipher_char_codes) {
//get index of character
int index = Integer.parseInt(code);
if (index > 26) {
char[] pair = code.toCharArray();
for (int i = 0; i < pair.length; i++) {
int x = Integer.parseInt("" + code.charAt(i));
message.append((char) ('a' + ((x - 1) % 26)));
}
} else {
//map index into 1 to 26
//find ascii code and cast into char
message.append((char) ('a' + ((index - 1) % 26)));
}
}
return message.toString();
}
}
Regex is indeed the way to go, and the code proposed by Pirate_Jack can be improved. It calls the expensive regex two superfluous times (replace is a regex operation).
Following is a yet improved version:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class Julia3 {
public static void main(final String[] args) {
final String s = "10#21#12#91";
final String result = decrypt(s);
System.out.println(result);
}
public static String decrypt(final String msg) {
final Pattern regex = Pattern.compile("((\\d\\d)(#)|(\\d))");
final Matcher regexMatcher = regex.matcher(msg);
final StringBuffer result = new StringBuffer();
String c;
while (regexMatcher.find()) {
if (regexMatcher.group(2) == null) {
c = regexMatcher.group(1);
} else {
c = regexMatcher.group(2);
}
result.append((char) ((Integer.parseInt(c) + 'a') - 1));
}
return result.toString();
}
}
This is not right :
hs.get(s)
s is a StringBuilder. It should be hs.get(Char)
Edit: an optional different solution:
public class Julia {
public static void main(String[] args) {
String s="10#21#12#91";
List<String> numbers = splitToNumbers(s);
Julia obj=new Julia();
String result=obj.decrypt(numbers);
System.out.println(result);
}
/**
*#param s
*#return
*/
private static List<String> splitToNumbers(String s) {
//add check s is not null
char[] chars = s.toCharArray();
char delimiter = '#';
List<String> numberAsStrings = new ArrayList<String>();
int charIndex = 0;
while (charIndex < (chars.length -3)) {
char theirdChar = chars[charIndex+2];
if(theirdChar == delimiter) {
numberAsStrings.add(""+chars[charIndex]+chars[charIndex+1]);
charIndex +=3;
}else {
numberAsStrings.add(""+chars[charIndex]);
charIndex ++;
}
}
//add what's left
while (charIndex < chars.length) {
numberAsStrings.add(""+chars[charIndex]);
charIndex++;
}
return numberAsStrings;
}
public String decrypt(List<String> numbersAsStings){
StringBuilder sb=new StringBuilder();
for (String number : numbersAsStings) {
int num = Integer.valueOf(number);
sb.append(intToChar(num-1));
}
return sb.toString();
}
private char intToChar(int num) {
if((num<0) || (num>25) ) {
return '?' ;
}
return (char)('a' + num);
}
}

Replace all instances of a character in a String

I'm trying to create a method that replace all instances of a certain character in a word with a new character. This is what I have so far:
public class practice {
public static void main(String[] args) {
String test3 = updatePartialword("----", "test", 't');
System.out.println(test3); }
public static String updatePartialword(String partial, String secret, char c) {
String newPartial = "";
int len = secret.length();
for (int i=0; i<=secret.length()-1; i++){
char x = secret.charAt(i);
if (c==x) {
String first = partial.substring(0,i);
String second = partial.substring(i+1,len);
newPartial = first+x+second;
}
}
return newPartial;
}
}
I want it to return t--t, but it will only print the last t. Any help would be greatly appreciated!
Java already has a built in method in String for this. You can use the the replace() method to replace all occurrences of the given character in the String with the another character
String str = "Hello";
str.replace('l', '-'); //Returns He--o
str.replace('H', '-'); //Returns -ello
I suspect you are looking for something like
public static void main(String[] args) {
String test3 = updatePartialword("----", "test", 't');
System.out.println(test3);
}
public static String updatePartialword(String partial, String secret, char c) {
char[] tmp = partial.toCharArray();
for (int i = 0; i < secret.length(); i++) {
char x = secret.charAt(i);
if (c == x) {
tmp[i] = c;
}
}
return new String(tmp);
}
In your code you overwrite the String each time you found the character. Instead of overwriting, you should expand the string each time.
public class practice {
public static void main(String[] args) {
String test3 = updatePartialword("----", "test", 't');
System.out.println(test3);
}
public static String updatePartialword(String partial, String secret, char c) {
StringBuilder sb = new Stringbuilder();
sb.append(""); // to prevent the Stringbuilder from calculating with the chars
for (int i = 0; i < partial.lenght; i++)
if (secret.charAt(i) == c)
sb.append(c);
else
sb.append('-');
return sb.toString();
}
}

Categories

Resources