Finding patterns in strings using basic Java methods - java

say we have a string with these characters
"ABGCCFFGTBG"
then we have another string with characters "GECCCDOABG"
So the pattern is the prefix and suffix but if your given strings larger then this but have common prefix and suffix patterns how to pull those out into a substring in java. Keep in mind we dont always know the characters in the string were getting we just know there is a pattern in it.
my start is something like this
for(int i = 0. i < strA.length(); i++)
{
for(int j = 0; j < strB.length(); j++)
{
if(strA.charAt(i) == strB.charAt(j))
{
String subPattern = strA.substring(0,i);
String subPattern2 = strB.substring(0,j);
}
}
}
but this doesn't work. Any ideas?

Try to select best-matched pattern at first:
public static void main(String[] args) {
String strA = "ABGCCFFGTBG";
String strB = "GECCCDOABG";
System.out.println("Pattern: " + findPattern(strA, strB));
}
public static String findPattern(String strA, String strB) {
for (int length = Math.min(strA.length(), strB.length()); length > 0; length--) {
for (int i = 0; i <= strA.length() - length; i++) {
String pattern = strA.substring(i, i + length);
if (strB.contains(pattern)) {
return pattern;
}
}
}
throw new NoSuchElementException("No common pattern between " + strA + " and " + strB);
}
Output:
Pattern: ABG

this solution will find a pattern, no matter where it is in the string:
public static void main(String[] args) {
String strA = "uioABCDqwert";
String strB = "yxcvABCDwrk";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strA.length(); i++) {
for (int j = 0; j < strB.length(); j++) {
if (strA.charAt(i) == strB.charAt(j)) {
sb.append(strB.charAt(j));
i++;
}
}
if (sb.length() > 0)
break;
}
System.out.println(sb.toString());
}
this should give you an idea how it could be done

Related

program that takes an input parameter as a string and return the alternate words in it with “abc”. Words are separated by dots

Write a function that takes an input parameter as a string and return the alternate words in it with “abc”. Words are separated by dots.
Note: Avoid using inbuilt functions
Input: "i.like.this.program.very.much"
Output: "i.abc.this.abc.very.abc"
Would something like this work?
public String func(String s) {
String[] arr = s.split("\\.");
for (int i = 0; i < arr.length; i++) {
if (i % 2 == 1)
arr[i]= "abc";
}
String rString = "";
for (int i = 0; i < arr.length - 1; i++) {
rString += arr[i];
rString += ".";
}
rString += arr[arr.length - 1];
return rString;
}
Not my most efficient work, but it was what I came up with on the spur of the moment.
Not sure what you exactly mean by avoiding built in methods, but this should work:
public String whyNot(String s) {
String[] sA = s.split("\\.");
String newS = sA[0];
for (int i = 1; i < sA.length; i=i+2) {
newS += ".abc." + sA[i];
}
return newS;
}
**
public class Main
{
public static void main(String[] args) {
String a="i.like.this.program.very.much.";
String[]arr=a.split("\\.");
for(int i=0;i<=arr.length-1;i++){
if(i%2==1)
arr[i]="abc";
}
String rs="";
for(int i=0;i<arr.length-1;i++){
rs+=arr[i];
rs+=".";
}
rs+=arr[arr.length-1];
System.out.println(rs);
}
}
**

parsing/converting task with characters and numbers within

It is necessary to repeat the character, as many times as the number behind it.
They are positive integer numbers.
case #1
input: "abc3leson11"
output: "abccclesonnnnnnnnnnn"
I already finish it in the following way:
String a = "abbc2kd3ijkl40ggg2H5uu";
String s = a + "*";
String numS = "";
int cnt = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
numS = numS + ch;
cnt++;
} else {
cnt++;
try {
for (int j = 0; j < Integer.parseInt(numS); j++) {
System.out.print(s.charAt(i - cnt));
}
if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {
System.out.print(s.charAt(i));
}
} catch (Exception e) {
if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {
System.out.print(s.charAt(i));
}
}
cnt = 0;
numS = "";
}
}
But I wonder is there some better solution with less and cleaner code?
Could you take a look below? I'm using a library from StringUtils from Apache Common Utils to repeat character:
public class MicsTest {
public static void main(String[] args) {
String input = "abc3leson11";
String output = input;
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(input);
while (m.find()) {
int number = Integer.valueOf(m.group());
char repeatedChar = input.charAt(m.start()-1);
output = output.replaceFirst(m.group(), StringUtils.repeat(repeatedChar, number));
}
System.out.println(output);
}
}
In case you don't want to use StringUtils. You can use the below custom method to achieve the same effect:
public static String repeat(char c, int times) {
char[] chars = new char[times];
Arrays.fill(chars, c);
return new String(chars);
}
Using java basic string regx should make it more terse as follows:
public class He1 {
private static final Pattern pattern = Pattern.compile("[a-zA-Z]+(\\d+).*");
// match the number between or the last using regx;
public static void main(String... args) {
String s = "abc3leson11";
System.out.println(parse(s));
s = "abbc2kd3ijkl40ggg2H5uu";
System.out.println(parse(s));
}
private static String parse(String s) {
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
int num = Integer.valueOf(matcher.group(1));
char prev = s.charAt(s.indexOf(String.valueOf(num)) - 1);
// locate the char before the number;
String repeated = new String(new char[num-1]).replace('\0', prev);
// since the prev is not deleted, we have to decrement the repeating number by 1;
s = s.replaceFirst(String.valueOf(num), repeated);
matcher = pattern.matcher(s);
}
return s;
}
}
And the output should be:
abccclesonnnnnnnnnnn
abbcckdddijkllllllllllllllllllllllllllllllllllllllllggggHHHHHuu
String g(String a){
String result = "";
String[] array = a.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
//System.out.println(java.util.Arrays.toString(array));
for(int i=0; i<array.length; i++){
String part = array[i];
result += part;
if(++i == array.length){
break;
}
char charToRepeat = part.charAt(part.length() - 1);
result += repeat(charToRepeat+"", new Integer(array[i]) - 1);
}
return result;
}
// In Java 11 this could be removed and replaced with the builtin `str.repeat(amount)`
String repeat(String str, int amount){
return new String(new char[amount]).replace("\0", str);
}
Try it online.
Explanation:
The split will split the letters and numbers:
abbc2kd3ijkl40ggg2H5uu would become ["abbc", "2", "kd", "3", "ijkl", "40", "ggg", "2", "H", "5", "uu"]
We then loop over the parts and add any strings as is to the result.
We then increase i by 1 first and if we're done (after the "uu") in the array above, it will break the loop.
If not the increase of i will put us at a number. So it will repeat the last character of the part x amount of times, where x is the number we found minus 1.
Here is another solution:
String str = "abbc2kd3ijkl40ggg2H5uu";
String[] part = str.split("(?<=\\d)(?=\\D)|(?=\\d)(?<=\\D)");
String res = "";
for(int i=0; i < part.length; i++){
if(i%2 == 0){
res = res + part[i];
}else {
res = res + StringUtils.repeat(part[i-1].charAt(part[i-1].length()-1),Integer.parseInt(part[i])-1);
}
}
System.out.println(res);
Yet another solution :
public static String getCustomizedString(String input) {
ArrayList<String > letters = new ArrayList<>(Arrays.asList(input.split("(\\d)")));
letters.removeAll(Arrays.asList(""));
ArrayList<String > digits = new ArrayList<>(Arrays.asList(input.split("(\\D)")));
digits.removeAll(Arrays.asList(""));
for(int i=0; i< digits.size(); i++) {
int iteration = Integer.valueOf(digits.get(i));
String letter = letters.get(i);
char c = letter.charAt(letter.length()-1);
for (int j = 0; j<iteration -1 ; j++) {
letters.set(i,letters.get(i).concat(String.valueOf(c)));
}
}
String finalResult = "";
for (String str : letters) {
finalResult += str;
}
return finalResult;
}
The usage:
public static void main(String[] args) {
String testString1 = "abbc2kd3ijkl40ggg2H5uu";
String testString2 = "abc3leson11";
System.out.println(getCustomizedString(testString1));
System.out.println(getCustomizedString(testString2));
}
And the result:
abbcckdddijkllllllllllllllllllllllllllllllllllllllllggggHHHHHuu
abccclesonnnnnnnnnnn

how to convert "user_id" to "userId" in Java? [duplicate]

This question already has answers here:
What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?
(22 answers)
Closed 7 years ago.
convert string to camelCase
eg:
"user_id" to "userId"
"user_name" to "userName"
"country_province_city" to "countryProvinceCity"
how to do that in a easy way?
ps:"country_province_city" should be "countryProvinceCity" not "countryprovincecity"
I would use a loop and a StringBuilder. Something like
String[] arr = { "user_id", "user_name", "country_province_city" };
for (String str : arr) {
StringBuilder sb = new StringBuilder(str);
int pos;
while ((pos = sb.indexOf("_")) > -1) {
String ch = sb.substring(pos + 1, pos + 2);
sb.replace(pos, pos + 2, ch.toUpperCase());
}
System.out.printf("%s = %s%n", str, sb);
}
And I get the (requested)
user_id = userId
user_name = userName
country_province_city = countryProvinceCity
As Fast Snail mentions, simply use, for example, if String str = "user_id, user_name, user_id";, call str = str.replaceAll("userID", "user_id");, causing str to now have the value "userID, user_name, userID"
Alternatively, a more complete method would be as follows
public String toCamel(String str) {
String[] splits = str.split("_");
for (int i = 1; i < splits.length; i++) {
char first = Character.toUpperCase(splits.charAt(0));
if (splits[i].length() > 0)
splits[i] = first + splits[i].substring(1);
else
splits[i] = first + "";
}
String toRet = "";
for (String s : splits)
toRet += s;
return toRet;
}
This is a very simple one:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String result = "";
String input = scan.nextLine();
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '_') {
result += input.toUpperCase().charAt(i + 1);
i = i + 1;
} else {
result += input.toLowerCase().charAt(i);
}
}
System.out.println(result);
}
if you like to do it many times, I advice you to use a while loop to keep repeating the same code over and over again:
while (true) {
//the previous code
}
http://commons.apache.org/proper/commons-lang/javadocs/api-3.4/index.html
String str="country_province_city";
wordUtils.capitalize(str, '_');
str=str.replaceAll("_", "");
output: countryProvinceCity
For another point of view that the answers above you can also do it with split function and two loops, like this:
String[] strings = {"user_id","user_name","country_province_city"};
for (int i = 0; i < strings.length; i++)
{
String string = strings[i];
String totalString = "";
String[] divide = string.split("_");
for(int j = 0; j < divide.length; j++)
{
if(j != 0)
{
divide[j] = "" + divide[j].toUpperCase().charAt(0) + divide[j].substring(1,divide[j].length());
}
totalString = totalString + divide[j];
}
}
If you want to show this changed Strings by console you just have to add System.out.println after the second loop and inside the first one, like this:
for (int i = 0; i < strings.length; i++)
{
//The same code as the code that I put in the example above
for(int j = 0; j < divide.length; j++)
{
//The same code as the example above
}
System.out.println(totalString);
}
On the contrary, if your objective it's to store them into an array, you can do it like this:
String[] store;
for (int i = 0; i < strings.length; i++)
{
//The same code as the code that I put in the example above
store = new String[divide.length];
for(int j = 0; j < divide.length; j++)
{
//The same code as the example above
}
store[j] = totalString;
}
If you have any doubt about the code please let me know.
I expect it will help to you!

Add x number of spaces between the letters of a string in Java?

I need to recieve a integer and have it print out that number of spaces in between the letters of a name. Right now I have it printing out one space.
public static void printLongName(int spaces){
String name
char[] letter = name.toCharArray();
for(int i = 0; i < letter.length; i++)
System.out.print(" " + letter[i]);
System.out.println();
}
public static void printLongName(String name, int numOfSpacesBetweenLetters) {
StringBuffer sbSpace = new StringBuffer();
for (int i = 0; i <= numOfSpacesBetweenLetters; i++) {
sbSpace.append(" ");
}
char[] letter = name.toCharArray();
for (int i = 0; i < letter.length; i++) {
System.out.println(sbSpace + letter[i]);
}
}
use System.out.format()
System.out.format("%10c", letter[i]);
update
int spaces=10;
String name ="aaaaaaaa";
char[] letter = name.toCharArray();
for(int i = 0; i < letter.length; i++)
System.out.format("%10c", letter[i]);
//System.out.print(" " + letter[i]);
//System.out.print(getSpace(10) + letter[i]);like this you can
public String getSpace(int count)
{
String space="";
for(int i=0;i<count;i++)
space+=" ";
return space;
}
I believe your looking for something like this:
System.out.format("[%13s]%n", ""); // prints "[ ]" (13 spaces)
System.out.format("[%1$3s]%n", ""); // prints "[ ]" (3 spaces)
This regular expression will allow you to add your spaces appropriately.
You need build the space string first with parameter input. Please look at below code:
public static void printLongName(int spaces){
String name = "hello";
StringBuilder sb = new StringBuilder();
String spaceStr = "%"+spaces+"c";
char[] letter = name.toCharArray();
for(int i = 0; i < letter.length; i++) {
if (i == 0) {
sb.append(letter[i]);
} else {
sb.append(String.format(spaceStr, letter[i]));
}
}
System.out.println(sb);
}
public static void main(String[] args) {
printLongName(4);
}
Update some code.
This function will return a string with spaces:
String nameWithSpaces(String name, int spaces) {
StringBuilder sbname = new StringBuilder(name);
String spaces = String.valueOf(new char[spaces]).replace("\0", " ");
for (int i=1; i < sbname.length(); i += spaces.length()+1)
sbname.insert(i, spaces);
return sbname.toString();
}

How to find the longest repeated substring of given string

I am new java and I was given assignment to find the longest substring of a string.
I research online and seems that good way of approaching this problem will be implementing suffix tree.
Please let me know how I can do this or if you have any other solutions. keep in mind this is suppose to be done with low level of java knowledge.
Thanks in adavance.
P.S. the tester string is reassuring.
/**
This method will find the longest substring of a given string.
String given here is reassuring.
*/
public String longestRepeatedSubstring()
{
String longestRepeatedSubstring = "";
for (int i = 0; i<text.length(); i++ )
{
String one = text.substring(0,i);
for(int o = 0; o<text.length();o++)
{
Sting two = text.substring(0,o);
if(one.equals(two))
{
longestRepeatedSubstring = one;
}
}
}
return longestRepeatedSubstring;
}
If you debug your code you will see that you the code isn't doing what you think. AFAIK you need at least three loops and you can't assume you would only start from the first character. Here is one possible solution.
public static void main(String[] args) throws IOException {
String longest = longestDuplicate("ababcaabcabcaab");
System.out.println(longest);
}
public static String longestDuplicate(String text) {
String longest = "";
for (int i = 0; i < text.length() - 2 * longest.length() * 2; i++) {
OUTER:
for (int j = longest.length() + 1; j * 2 < text.length() - i; j++) {
String find = text.substring(i, i + j);
for (int k = i + j; k <= text.length() - j; k++) {
if (text.substring(k, k + j).equals(find)) {
longest = find;
continue OUTER;
}
}
break;
}
}
return longest;
}
prints
abcaab
for "reassuring" it prints r not s which was my first guess. ;)
public static void main(String[] args) {
String str = "testingString";
char[] strArr = str.toCharArray();
StringBuilder bm = new StringBuilder();
boolean isPresent = false;
int len = strArr.length;
int initial =0;
int dinitial=0;
HashMap<String, String> hm = new HashMap<String,String>();
HashMap<String, String> hl = new HashMap<String,String>();
while(initial<=len-1 && !(dinitial>=len-1)){
if(!hm.isEmpty()){
isPresent = hm.containsValue(strArr[initial]+"");
if(!isPresent){
bm.append(strArr[initial]);
hm.put(strArr[initial]+"",strArr[initial]+"");
if(initial==len-1){
System.out.println("Longest substring is::" + bm);
break;
}
}
else if(isPresent){
System.out.println("Longest substring is::" + bm);
bm.delete(0, bm.length());
++dinitial;
initial--;
hm.clear();
}
initial++;
}
else
{
bm.append(strArr[initial]);
hm.put(strArr[initial]+"",strArr[initial]+"");
initial++;
}
}
hm.clear();
}

Categories

Resources