I can not count matching string from another string - java

String s1 = "aabbccaa";
String s2 = "aa";
I need to count how many times s2 repeated in s1. I tried split text with no luck. Can someone help?
String s1 ="aabbccaa";
String s2 = "aa";
int count = 0;
for(int i = 0; i < s1.length(); i++) {
for(int j = 0; j < s2.length(); j++) {
if(s1.charAt(i) == s2.charAt(j)) {
count++;
}
}
}
System.out.println(count);
}
}

public class Solution {
public static void main(String[] args) {
String s1 ="aabbccaassssASaatestaa";
String s2 = "aa";
// split the string S1 by s2
String a[] = s1.split(s2);
//Output will be 4 - because 'aa' 4 times in s1
System.out.println(a.length);
}
}
Output - 4
In case of overlapping you can use the 'matcher' to get the count of match string in other.
https://www.tutorialspoint.com/javaregex/javaregex_matcher_replaceall.htm
String s1 ="aaaassssaassaass";
String s2 = "aa";
Pattern pattern =Pattern.compile(s2);
Matcher matcher = pattern.matcher(s1);
int i = 0;
while(matcher.find()){
i++;
}
//Out put will be 4
System.out.println(i);
Working Demo

I use Regex. Not sure if this is what you want
Create a parttern from input s2 and match it with s1.
Match will create a list matcher and count it which is the answer.
public int countString(String s1, String s2) {
Pattern pattern = Pattern.compile(s2);
Matcher matcher = pattern.matcher(s1);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
Output is 2

You can use the indexOf method.
String indexOf(String str) : This method returns the index within this string of the first occurrence of the specified substring. If it does not occur as a substring, -1 is returned.

Related

How to check if character at current index in for loop is a specific character (e.g. the letter A, the number 2, etc)?

I'm building a simple program in Java that finds letters in strings and replaces them with a number, but I'm having trouble finding a method that will allow me to check for the exact specific character. There are plenty for digits and letters in general.
As my for loop stands now, it just replaces the letter everywhere, irregardless of whether it is within the range specified by start and end.
Any help would be appreciated.
String str = "A.A.A.A.A.A.A.A";
int start = 3;
int end = 9;
for (int i = start; i < end; i++) {
if (Character.isLetter(str.charAt(i)) {
str = str.replaceAll("A", "9");
return str;
Expected Output:
A.A.9.9.9.A.A.A
Actual Output:
9.9.9.9.9.9.9.9
In your code, you have
str = str.replaceAll("A", "9");
This will replace all the occurrences of A to 9
Instead of your approach, you should
1.Convert the string to a char array
char[] charArray = str.toCharArray();
2.Then replace each occurrence of character with a number
if (Character.isLetter(charArray[i])){
//Character Found
charArray[i] = '9';
}
3. Convert it back to string using
str = String.valueOf(charArray);
Modified Code:
String str = "A.A.A.A.A.A.A.A";
int start = 3;
int end = 9;
//Converting String to char array
char[] charArray = str.toCharArray();
for (int i = start; i < end; i++) {
if (Character.isLetter(charArray[i])){
//Character Found
charArray[i] = '9';
}
}
//Converting Back to String
str = String.valueOf(charArray);
System.out.println(charArray);
System.out.println(str);
Compare for character equality and then use string builder to replace the specified character
//Use of StringBuffer preferred over String as String are immutable
StringBuilder sb = new StringBuilder(str);
// -1 to start as index start from 0
for (int i = start-1; i < end; i++) {
char currentChar = currentString.charAt(i);
if (currentChar == "A") {
sb.setCharAt(i, '9');
}
}
return sb.toString();
I'd do it that way. Cut out the string to isolate the part you want to act on, do your replace ans stitch it all back together :
String str = "A.A.A.A.A.A.A.A";
int startIndex = 3;
int endIndex = 9;
String beginning = str.substring(0, startIndex);
String middle = str.substring(startIndex, endIndex);
String end = str.substring(endIndex);
middle = middle.replaceAll("A", "9");
String result = beginning + middle + end;
System.out.println(result);
Prints out :
A.A.9.9.9.A.A.A
EDIT:
As suggested in the comments, you could do it in one line
String str = "A.A.A.A.A.A.A.A";
int startIndex = 3;
int endIndex = 9;
String result =
str.substring(0, startIndex) +
str.substring(startIndex, endIndex).replaceAll("A", "9") +
str.substring(endIndex);
Here is an example using substrings to let you choose what portion of the string you want to test
int start = 3;
int end = 9;
String str = "A.A.A.A.A.A.A.A";
String startStr = str.substring(0,start);
String endStr = str.substring(end);
String newStr="";
char temp=' ';
for (int i = start; i < end; i++) {
temp = str.charAt(i);
if (temp=='A')
newStr+="9";
else
newStr += temp;
}
return(startStr + newStr + endStr);
You are replacing all the match found in the string and not specifying the index that needs to be replaced.
Use the StringBuffer replace method like below:
public static void main(String[] args) {
String str = "AAAAAAAA";
int start = 3;
int end = 9;
str = replaceBetweenIndexes(str, start, end, "9"); // AAA999AA
str = replaceBetweenIndexes("ABCD6EFG", start, end, "3"); // ABC363FG
}
public static String replaceBetweenIndexes(String str, int start, int end, String replaceWith) {
StringBuffer strBuf = new StringBuffer(str);
for (int i = start; i < end; i++) {
if (Character.isLetter(strBuf.charAt(i)) {
strBuf.replace(i, i+1, replaceWith);
}
}
return strBuf.toString();
}

How to switch two characters in a string?

Given a string as input, return the string with its last 2 chars swapped. And, if the string has less than 2 chars, do nothing and return the input string.
Here is the code I wrote so far:
public class SwapLastChars {
static String testcase1 = "Hello";
public static void main(String args[]) {
SwapLastChars testInstance = new SwapLastChars();
String result = testInstance.swap(testcase1);
System.out.println(result);
}
public String swap(String str1) {
String str = "";
int length = str1.length();
char last = str1.charAt(length - 1);
char l = str1.charAt(length - 2);
if (length == 1)
return str1;
for (int i = 0; i < str1.length() - 2; i++) {
str = str + str1.charAt(i);
}
str = str + last + l;
return str;
}
}
Problem is in my test cases,any help?
Testcase Pass/Fail Parameters Actual Output Expected Output
1 pass 'aabbccdd' aabbccdd aabbccdd
2 fail 'A' null A
3 pass 'hello' helol helol
If you pass "A" you'll get StringIndexOutOfBoundsException rather than null. Unless you suppress it in a catch clause and return null.
Quick fix. Move the length check to start of the method. That should solve your issue.
public class SwapLastChars {
static String testcase1 = "A";
public static void main(String args[]) {
SwapLastChars testInstance = new SwapLastChars();
String result = testInstance.swap(testcase1);
System.out.println(result);
}
public String swap(String str1) {
if(str1 == null || str1.length() < 2) { //Move here
return str1;
}
String str = "";
int length = str1.length();
char last = str1.charAt(length - 1);
char l = str1.charAt(length - 2);
for(int i = 0; i < str1.length() - 2; i++) {
str = str + str1.charAt(i);
}
str = str + last + l;
return str;
}
}
You should check for length at the very beginning of your function.
public String swap(String str1){
String str="";
int length=str1.length();
if (length <=2)
return str1;
char last=str1.charAt(length-1);
char l=str1.charAt(length-2);
for(int i=0;i<str1.length()-2;i++)
{
str=str+str1.charAt(i);
}
str=str+last+l;
return str;
}
I know this has already been answered, but I feel OPs swap method can be simplified by using a StringBuilder:
public static String swap(String word) {
//Answer by Syam
if (word == null || word.length() < 2) {
return word;
}
//Create new StringBuilder
StringBuilder s = new StringBuilder(word);
//Get second last char
char c = s.charAt(s.length() - 2);
//Replace second last char with last char
s.setCharAt(s.length() - 2, s.charAt(s.length() - 1));
//replace last char with stored char
s.setCharAt(s.length() - 1, c);
return s.toString();
}
Run:
System.out.println(swap("aabbccdd"));
System.out.println(swap("A"));
System.out.println(swap("hello"));
Output:
aabbccdd
A
helol
And here is why

Java String replace

Lets say I have a string "aabbccaa". Now I want to replace occurrences of "aa" in given string by another string. But it should be in following way.
First occurrence of "aa" should be replaced by "1" and next occurrence of "aa" by "2" and so on.
So, the result of the string becomes "1bbcc2".
You can use replaceFirst() in a for loop where counter is incrementing...
for (int i = 1; string.contains("aa"); i++) {
string = string.replaceFirst("aa", "" + i);
}
You can do it using the Matcher's appendReplacement method:
Pattern p = Pattern.compile("aa");
Matcher m = p.matcher("aabbccaahhhaahhhaaahahhahaaakty");
StringBuffer sb = new StringBuffer();
// Variable "i" serves as a counter. It gets incremented after each replacement.
int i = 0;
while (m.find()) {
m.appendReplacement(sb, ""+(i++));
}
m.appendTail(sb);
System.out.println(sb.toString());
This approach lets you avoid creating multiple string objects (demo).
It is possible to do using Java functions but using a char array and doing it using a lower level of logic would be faster.
String s = "aabbccaa";
String target = "aa";
int i = 1;
String newS;
for (int j = 0; j < s.length; j++) {
newS = s.replaceFirst(target, i++);
j += newS.length - s.length;
s = newS;
}
Here is a solution :
public static void main(String[] a) {
int i = 1;
String before = "aabbccaabbaabbaa";
String regex = "aa";
String after = substitute(i, before, regex);
System.out.println(after);
}
private static String substitute(int i, String before, String regex) {
String after = before.replaceFirst(regex, Integer.toString(i++));
while (!before.equals(after)) {
before = after;
after = before.replaceFirst(regex, Integer.toString(i++));
}
return after;
}
Output :
1bbcc2bb3bb4

Partially Equal strings and the index of the shared charachter

If I want to evaluate that two strings are partially equal, I can use contains
like "Hello".contains"heu"
but my question is how to get the indexes of the characters that are equal?
You could use Pattern and matcher classes.
String s1 = "Hello";
String s2 = "he";
Matcher m = Pattern.compile("(?i)" + s2).matcher(s1);
while (m.find()) {
System.out.println(m.start());
}
Output:
0
One of the simplest way to do is use String.indexOf() method
public class StringTest {
public static void main(String...strings){
String s="hello";
System.out.println(s.indexOf("he"));
}
}
Output 0
This is how I solve it:
public static int[] partiallyEqualColumns(String columnAtt1, String columnAtt2)
{
int[] sharedColumn = new int[2];
String att;
String[] array1 = columnAtt1.trim().split(" ");
String[] array2 = columnAtt2.trim().split(" ");
for(int i = 0 ; i < array1.length;i++)
{
for(int j =0; j <array2.length; j++)
{
if(array1[i].equals(array2[j]))
{
att = array1[i];
sharedColumn[0] = i;
sharedColumn[1] = j;
return sharedColumn;
}
}
}
return sharedColumn;
}

Validating an Array with least number of numeric Characters

I have an array of strings:
void populateStringArray()
{
toppings = new String[20];
toppings[0] = "Cheese12";
toppings[1] = "Pepperoni1234";
toppings[2] = "Black Olives1";
// ...
And I want to return the one with least numeric characters.
Can some one suggest the logic to achieve this?
If using Guava is an Option, you can just do this:
int digitChars = CharMatcher.DIGIT.countIn(yourString)
You can count the number of digits in a string str with
str.length() - str.replaceAll("\\d", "").length()
Simple as pie.
Now all you have to do is loop over your array toppings and find the string s for which str.length() - str.replaceAll("\\d", "").length() is least.
You can loop over characters and use Character.isDigit() to count digits in the string.
String str = "Cheese12";
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
count++;
}
}
System.out.println(count);
Output:
2
Pattern p = Pattern.compile("-?\\d+"); //regex pattern to find integers on a string
int index = 0;
int test;
int lowest = Integer.MAX_VALUE;
for (int i : toppings.size()-1){
Matcher m = p.matcher(toppings[i]);
if (m.find()) { //assuming only one number to find
test = Integer.parseInt(m.group());
if (test < lowest){
lowest = test;
index = i;
}
}
}
return patterns[index]; //in case of tie the lowest index wins
You can find all digits in your string using regex and count the number of digits:
public int getNumberOfDigitsInString(String input) {
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find())
count += matcher.group().length();
return count;
}
Now you can just iterate over your array and find the one with the least amount of digits:
int lowestN = Integer.MAX_VALUE;
String finalString = "";
for (String str:toppings) {
int currentN = getNumberOfDigitsInString(str);
if (lowestN > currentN) {
finalStr = str;
lowestN = currentN;
}
}
System.out.println("Result: " + finalStr + " (has " + lowestN + " digits in it)");
String leastChar(){
int leastChar=Integer.MAX_VALUE;
String leastTopping=null;
int eachToppingTemp=0;
for (String topping:toppings){
if (topping==null) continue;
eachToppingTemp= Integer.MAX_VALUE;
for (char eachChar:topping.toCharArray()){
if (Character.isDigit(eachChar)){
eachToppingTemp++;
}
}
if (eachToppingTemp<leastChar){
leastChar=eachToppingTemp;
leastTopping=topping;
}
}
System.out.println("Lowest char topping : "+leastTopping);
return leastTopping;
}

Categories