Im trying to write a segment of code that will request from the user two Strings. How can i write code so that forms a new String by alternating the characters of the two Strings.
Any help is appreciated
Simple "dumb" approach :)
class StringMerge
{
public static String merge(String a, String b)
{
if (a == null || a.length() == 0){ return b; }
else if(b == null || b.length() == 0){ return a; }
else
{
StringBuffer merged = new StringBuffer();
int aIndex = 0;
int bIndex = 0;
while(aIndex < a.length() && bIndex < b.length())
{
merged.append(a.charAt(aIndex));
merged.append(b.charAt(bIndex));
aIndex++;
bIndex++;
}
while(aIndex < a.length())
{
merged.append(a.charAt(aIndex));
aIndex++;
}
while(bIndex < b.length())
{
merged.append(b.charAt(bIndex));
bIndex++;
}
return merged.toString();
}
}
}
A slightly shorter and faster [due to StringBuilder] version of mohaps' approach:
class StringMerge {
public static String merge(final String a, final String b) {
if (a == null || a.length() == 0) {
return b;
} else if (b == null || b.length() == 0) {
return a;
} else {
final int aLength = a.length();
final int bLength = b.length();
final StringBuilder merged = new StringBuilder(aLength + bLength);
for (int i = 0, j = 0; i < aLength && j < bLength; i++, j++) {
merged.append(a.charAt(i)).append(b.charAt(j));
}
if (aLength != bLength) {
if (aLength > bLength) {
merged.append(a.substring(bLength));
} else {
merged.append(b.substring(aLength));
}
}
return merged.toString();
}
}
}
Edit: Added length while creating StringBuilder instance
Pretty much the same as mohaps and shams (smile), but using an array :
static public void main(String...args) {
Scanner scanner = new Scanner(System.in);
System.out.print("String 1 : ");
String s1 = scanner.nextLine();
System.out.print("String 2 : ");
String s2 = scanner.nextLine();
System.out.println("Combined string is : " + mergeStrings(s1, s2));
}
static public String mergeStrings(String a, String b) {
if (a == null) a = "";
if (b == null) b = "";
char[] chars = new char[a.length() + b.length()];
int index = 0, ia = 0, ib = 0;
while (ia<a.length() && ib<b.length()) {
chars[index++] = a.charAt(ia++);
chars[index++] = b.charAt(ib++);
}
while (ia<a.length()) {
chars[index++] = a.charAt(ia++);
}
while (ib<b.length()) {
chars[index++] = b.charAt(ib++);
}
return new String(chars);
}
** UPDATE **
A slightly improvement, added a start position (default to 0) to start merge at a specific position from a. If start is negative, the method will behave as if it were 0. If start is greater than the length of the string a, the string will be padded with spaces until start is reached.
static public String mergeStrings(String a, String b) {
return mergeStrings(a, b, 0);
}
static public String mergeStrings(String a, String b, int start) {
if (a == null) a = "";
if (b == null) b = "";
int len = Math.max(start - a.length(), 0) + a.length() + b.length();
char[] chars = new char[len];
int index = 0, ia = 0, ib = 0;
while (ia<a.length() && ia<start) {
chars[index++] = a.charAt(ia++);
}
while (index<start) {
chars[index++] = ' ';
}
while (ia<a.length() && ib<b.length()) {
chars[index++] = a.charAt(ia++);
chars[index++] = b.charAt(ib++);
}
while (ia<a.length()) {
chars[index++] = a.charAt(ia++);
}
while (ib<b.length()) {
chars[index++] = b.charAt(ib++);
}
return new String(chars);
}
Output :
String 1 : hello
String 2 : world
Combined string is : hweolrllod
Combined merged at 2 : helwloorld
Combined merged at 4 : helloworld
Combined merged at 10 : hello world
Assuming the user enters two strings of the same length:
Make a new, empty string.
Loop...
If Index % 2 == 0, take the character from the second string entered by the user and add it to the empty string.
Otherwise, take the character form the first string and add it to the empty string.
Stop the loop when there are no more characters to add.
Related
You are allowed to use the following methods from the Java API:
class String:
length,charAt
class StringBuilder:
length,charAt,append,toString
class Character: any method
moveAllXsRight takes a char and a String as input and returns a String.
The output string should be the same as the input string except that every occurrence of the input character should be shifted one character to the right. If it is impossible to shift a character to the right (it is at the end of the string), then it is not shifted. Do not use arrays to solve this problem.
HW2.moveAllXsRight('X', "abcXdeXXXfghXiXXjXX")
"abcdXefXXXghiXjXXXX"
Here is my code now:
public static String moveAllXsRight(char a, String b){
StringBuilder sb = new StringBuilder();
String str ="";
for ( int i = 0; i<b.length(); i++){
if(b.charAt(i) != a){
sb.append(b.charAt(i));
}
else if(b.charAt(i) == a){
str = Character.toString(b.charAt(i));
}
else {
if(b.charAt(i+2)>sb.length()){
sb.append(b.charAt(i));
}
}
}
return sb.toString();
}
Try this:
public static String moveAllXsRight(char a, String b) {
StringBuilder sb = new StringBuilder(b);
for(int i = 0; i < sb.length() - 1; i++) {
if(sb.charAt(i) == a) {
// swapping with the right character
sb.setCharAt(i, sb.charAt(i + 1));
sb.setCharAt(i + 1, a);
// skipping next index (because we already know it contains `a`)
i = i + 1;
}
}
return sb.toString();
}
For this example:
moveAllXsRight('X', "abcXdeXXXfghXiXXjXX");
This is the output:
abcdXeXXfXghiXXXjXX
Update:
By slightly changing the for loop (inverting it):
for(int i = sb.length() - 2; i > 0; i--) { // inverse loop
if(sb.charAt(i) == a) {
// swapping
sb.setCharAt(i, sb.charAt(i + 1));
sb.setCharAt(i + 1, a);
}
}
Now this:
moveAllXsRight('X', "abcXdeXXXfghXiXXjXX");
Results in:
abcdXefXXXghiXjXXXX
Now you can decide which version do you want to use.
Here's one way to do it:
public static String moveAllXsRight(char a, String b) {
char[] chars = b.toCharArray();
for (int i = 0; i < chars.length-1; ++i) {
if (chars[i] == a) {
chars[i] = chars[i+1];
chars[i+1] = a;
}
}
return new String(chars);
}
It gives "abcdeXXXfghXiXXjXXX" when the arguments are 'X' and "abcXdeXXXfghXiXXjXX".
Here's another way:
public static String moveAllXsRight(char a, String b) {
char[] chars = b.toCharArray();
boolean wasa = false;
for (int i = 0; i < chars.length; ++i) {
char c = chars[i];
if (wasa) {
chars[i-1] = c;
chars[i] = a;
}
wasa = c == a;
}
return new String(chars);
}
It gives "abcdXeXXfXghiXXjXXX".
UPDATE
Here's yet another way:
public static String moveAllXsRight(char a, String b) {
char[] chars = b.toCharArray();
for (int i = chars.length-1; --i >= 0;) {
char c = chars[i];
if (c == a) {
chars[i] = chars[i+1];
chars[i+1] = a;
}
}
return new String(chars);
}
It gives "abcdXefXXXghiXjXXXX" which is what you expected.
UPDATE 2:
With a StringBuilder to avoid using arrays:
public static String moveAllXsRight(char a, String b) {
StringBuilder buf = new StringBuilder(b);
for (int i = buf.length()-1; --i >= 0;) {
char c = buf.charAt(i);
if (c == a) {
buf.setCharAt(i, buf.charAt(i+1));
buf.setCharAt(i+1, a);
}
}
return buf.toString();
}
public static String moveAllXsRight(char a, String b){
String str ="";
int n = 0;
char lower_a = Character.toLowerCase(a);
char upper_a = Character.toUpperCase(a);
for ( int i = b.length()-2; i>=0; i--){
if(b.charAt(i) == lower_a || b.charAt(i) == upper_a){
n++;
}
}
str = b.substring(b.length()-n) + b.substring(0,b.length()-n);
return str;
}
import java.util.*;
public class Main_5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
for(int i = 0; i < m; i++){
String password = sc.nextLine();
System.out.println(got(password));
}
}
public static String got(String password) {
HashMap<Character, Integer> checkpass = new HashMap<>();
Character ch = null;
Integer val = 0;
int odd = 0, even = 0;
for (int i = 0; i < password.length(); i++) {
ch = password.charAt(i);
if (checkpass.containsKey(ch) == false) {
checkpass.put(ch, 1);
} else {
val = (Integer) checkpass.get(ch);
checkpass.put(ch, val + 1);
}
}
Set<Character> hashval = checkpass.keySet();
for (Character key : hashval) {
val = (Integer) checkpass.get(key);
if (val == password.length())
return "YES";
else if (val % 2 == 1)
odd++;
else
even++;
}
if (odd == 1 || odd == 0)
return "YES";
else
return "NO";
}
}
PLEASE TEST THIS OUT FOR YOURSELF
As you can see, there is integer m in the main method. When I hit run, it makes integer m as if it were part of the got method. This is a code to find if x Strings can be a permutation palindrome.
This should what the console should look like:
*Input*:
3
ccaabcbb
azzza
bbbbccccdddddddd
*Output*:
NO
YES
YES
Use sc.next() instead sc.nextLine() as its giving the empty line created by your first enter.
import java.util.*;
public class Main_5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
for(int i = 0; i < m; i++){
String password = sc.next();
System.out.println(got(password));
}
}
public static String got(String password) {
HashMap<Character, Integer> checkpass = new HashMap<>();
Character ch = null;
Integer val = 0;
int odd = 0, even = 0;
for (int i = 0; i < password.length(); i++) {
ch = password.charAt(i);
if (checkpass.containsKey(ch) == false) {
checkpass.put(ch, 1);
} else {
val = (Integer) checkpass.get(ch);
checkpass.put(ch, val + 1);
}
}
Set<Character> hashval = checkpass.keySet();
for (Character key : hashval) {
val = (Integer) checkpass.get(key);
if (val == password.length())
return "YES";
else if (val % 2 == 1)
odd++;
else
even++;
}
if (odd == 1 || odd == 0)
return "YES";
else
return "NO";
}
}
I my be wrong, but rewritting getting m to this:
int m = Integer.parseInt(sc.nextLine());
should do the trick. There is problem using scanner's nextInt() and reading new line from standard input.
I'm trying to write a function that takes in a String and returns the greatest number of consecutive equivalent vowels in the String.
Here's my attempt:
public static final String VOWELS = "aeiou";
public static int consecutiveVowelsInLine(String line) {
int longestVowels = 0;
int candidateLength = 0;
for (int i = 0; i < line.length() - 1; i++) {
if (isVowel(line.charAt(i))) {
if (line.charAt(i) == line.charAt(i+1)) {
candidateLength++;
}
} else {
candidateLength = 0;
}
longestVowels = Math.max(longestVowels, candidateLength);
}
return longestVowels;
}
public static boolean isVowel(char c) {
VOWELS.contains(c.toLowerCase());
}
The problem is this doesn't handle the case where the String is a single character that's a vowel. So if the String is just "a", my code gives back 0 instead of 1.
As said before, the vowels have to be the same.
Testcases:
a -> 1
b -> 0
ae -> 1
aeae -> 1
aab -> 2
aba -> 1
abee -> 2
I think you aim to do too much in the loop: instead of looking to the character next, concentrate on the current character and maintain a state that stores the previous vowel:
public static int consecutiveVowelsInLine(String line) {
int longestVowels = 0;
int candidateLength = 0;
char vowel = 'b'; //b is not a vowel
for (int i = 0; i < line.length(); i++) {
char ci = line.charAt(i);
if (isVowel(ci)) {
if (ci == vowel) { //the same as the other one
candidateLength++;
} else {
candidateLength = 1;
}
vowel = ci;
} else {
candidateLength = 0;
vowel = 'b';
}
longestVowels = Math.max(longestVowels, candidateLength);
}
return longestVowels;
}
Here vowel stores the current vowel sequences you are working with. In the beginning we use b, simple because that is not a vowe. In case we encounter a vowel, that vowel is stores in vowel and we update the candidateLength accordingly. In case we encounter a non-vowel, we set vowel back to b (or another non-vowel).
Demo:
There were some problems with your isVowel method as well, a running implementation with a few testcases can be found here.
Here's one problem:
if (line.charAt(i) == line.charAt(i+1)) {
candidateLength++;
}
If the string is only one character, you're checking the character against null. Add a check, something like this:
if (line.length() == 1 && isVowel(line.charAt(0)) {
etc.
}
Simply change it like:
public static int consecutiveVowelsInLine( String line ){
int result = findConsecutiveMaxValue( line );
if( result == 0 ){
result = findSingleVowel( line );
}
return result;
}
private static int findSingleVowel( String line ){
for( int i = 0; i < line.length(); i++ ){
if( isVowel( line.charAt( i ) ) ){ return 1; }
}
return 0;
}
private static int findConsecutiveMaxValue( String line ){
int longestVowels = 0;
int candidateLength = 0;
for( int i = 0; i < line.length() - 1; i++ ){
if( isVowel( line.charAt( i ) ) ){
if( line.charAt( i ) == line.charAt( i + 1 ) ){
candidateLength++;
}
}
else{
candidateLength = 0;
}
longestVowels = Math.max( longestVowels, candidateLength );
}
return longestVowels;
}
Change:
if (line.charAt(i) == line.charAt(i+1)) {
candidateLength++;
}
to:
if (candidateLength == 0 || line.charAt(i) == line.charAt(i-1)) {
candidateLength++;
}
Additionally the condition in for() loop looks suspicious - use getLength() instead of getLength()-1.
Hi All I'm using the following function to check the Consecutive digits in java
The issue im facing here is it works for the first Consecutive digits only
For example it work for 123456789123456XXXX
but want this to work Consecutive any where
XXXX123456789123456 or XX123456789123456XX
Update
Now if i found 13 Consecutive digits then i need to pass all Consecutive digits to the mask function
and my result should be
something like this
for input 123456789123456XXXX result should be 123456%%%%%3456XXXX
for input XXXX123456789123456 result should be XX123456%%%%%3456XX
Please help me to solve this
My Code
public void checkPosCardNoAndMask(String cardNo) {
String maskNumber = "";
String starValue = "";
boolean isConsecutive = false;
int checkConsecutive = 0;
for (int i = 0, len = cardNo.length(); i < len; i++) {
if (Character.isDigit(cardNo.charAt(i))) {
maskNumber = maskNumber + cardNo.charAt(i);
} else {
if (checkConsecutive >= 13)
isConsecutive = true;
else
break;
starValue = starValue + cardNo.charAt(i);
}
checkConsecutive++;
}
if (isConsecutive)
{
cardNo = maskCCNumber(maskNumber) + starValue;
System.out.printIn("Consecutive found!!:"+cardNo);
}
else
{
System.out.printIn("Consecutive not found!!:"+cardNo);
}
}
Masking logic
public String maskCCNumber(String ccNo)
{
String maskCCNo = "";
for (int i = 0; i < ccNo.length(); i++)
{
if (i > 5 && i < ccNo.length() - 4)
{
maskCCNo = maskCCNo + '%';
}
else
{
maskCCNo = maskCCNo + ccNo.charAt(i);
}
}
return maskCCNo;
}
With regex you can do this way:
String str = "XX123456789123456XX";
if (str.matches(".*\\d{13}.*")) {
System.out.println(true);
Pattern compile = Pattern.compile("\\d+");
Matcher matcher = compile.matcher(str);
matcher.find();
String masked = maskCCNumber(matcher.group());//send 123456789123456 and returns 123456%%%%%3456
String finalString=str.replaceAll("\\d+", masked);// replace all digits with 123456%%%%%3456
System.out.println(finalString);
}
Output:
true
XX123456%%%%%3456XX
There are few issues:
You're breaking out of else, when first time you find non-digit character. This will skip any consecutive digit coming after that. So, you should not break.
In fact, you should add break out of the loop once you find 13 consecutive digit.
You're not really looking for consecutive digits, but just total number of non-cosnecutive digits. At least the current logic without break would work this way. You should reset the checkConsecutive variable to 0 when you find a non-digit character.
So, changing your for loop to this will work:
for (int i = 0, len = cardNo.length(); i < len; i++)
{
if (Character.isDigit(cardNo.charAt(i))) {
checkConsecutive++;
} else if (checkConsecutive == 13) {
isConsecutive = true;
break;
} else {
checkConsecutive = 0;
}
}
Of course I don't know what is starValue and maskValue, so I've removed it. You can add it appropriately.
BTW, this problem can also be solved with regex:
if (cardNo.matches(".*\\d{13}.*")) {
System.out.println("13 consecutive digits found");
}
try this
public void checkPosCardNoAndMask(String cardNo) {
if (cardNo.matches("[0-9]{13,}")) {
System.out.println("Consecutive found!!");
} else {
System.out.println("Consecutive not found!!");
}
}
If you want to work with your code then make one change
public void checkPosCardNoAndMask(String cardNo) {
String maskNumber = "";
String starValue = "";
boolean isConsecutive = false;
int checkConsecutive = 0;
for (int i = 0, len = cardNo.length(); i < len; i++) {
if (Character.isDigit(cardNo.charAt(i))) {
maskNumber = maskNumber + cardNo.charAt(i);
checkConsecutive++;
} else {
if (checkConsecutive >= 13)
{isConsecutive = true;break;}
else
checkConsecutive=0;
starValue = starValue + cardNo.charAt(i);
}
}
if (isConsecutive) {
System.out.printIn("Consecutive found!!");
} else {
System.out.printIn("Consecutive not found!!");
}
}
try this
public static void checkPosCardNoAndMask(String cardNo) {
int n = 1;
char c1 = cardNo.charAt(0);
for (int i = 1, len = cardNo.length(); i < len && n < 13; i++) {
char c2 = cardNo.charAt(i);
if (c2 >= '1' && c2 <= '9' && (c2 - c1 == 1 || c2 == '1' && c1 == '9')) {
n++;
} else {
n = 0;
}
c1 = c2;
}
if (n == 13) {
System.out.println("Consecutive found!!");
} else {
System.out.println("Consecutive not found!!");
}
}
My understanding is that you want to mask card numbers in a string. There is one external dependency in following code http://commons.apache.org/proper/commons-lang/ for StringUtils
/**
* Returns safe string for cardNumber, will replace any set of 13-16 digit
* numbers in the string with safe card number.
*/
public static String getSafeString(String str) {
Pattern CARDNUMBER_PATTERN = Pattern.compile("\\d{13,16}+");
Matcher matcher = CARDNUMBER_PATTERN.matcher(str);
while (matcher.find()) {
String cardNumber = matcher.group();
if (isValidLuhn(cardNumber)) {
str = StringUtils.replace(str, cardNumber, getSafeCardNumber(cardNumber));
}
}
return str;
}
public static boolean isValidLuhn(String cardNumber) {
if (cardNumber == null || !cardNumber.matches("\\d+")) {
return false;
}
int sum = 0;
boolean alternate = false;
for (int i = cardNumber.length() - 1; i >= 0; i--) {
int n = Integer.parseInt(cardNumber.substring(i, i + 1));
if (alternate) {
n *= 2;
if (n > 9) {
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
/**
* Returns safe string for cardNumber, will keep first six and last four
* digits.
*/
public static String getSafeCardNumber(String cardNumber) {
StringBuilder sb = new StringBuilder();
int cardlen = cardNumber.length();
if (cardNumber != null) {
sb.append(cardNumber.substring(0, 6)).append(StringUtils.repeat("%", cardlen - 10)).append(cardNumber.substring(cardlen - 4));
}
return sb.toString();
}
I am using this algorithm to find common substring between 2 strings. Please, help me to do this but with using Array of common substrings of this strings, which I should ignore in my function.
My Code in Java:
public static String longestSubstring(String str1, String str2) {
StringBuilder sb = new StringBuilder();
if (str1 == null || str1.isEmpty() || str2 == null || str2.isEmpty()) {
return "";
}
// java initializes them already with 0
int[][] num = new int[str1.length()][str2.length()];
int maxlen = 0;
int lastSubsBegin = 0;
for (int i = 0; i < str1.length(); i++) {
for (int j = 0; j < str2.length(); j++) {
if (str1.charAt(i) == str2.charAt(j)) {
if ((i == 0) || (j == 0)) {
num[i][j] = 1;
} else {
num[i][j] = 1 + num[i - 1][j - 1];
}
if (num[i][j] > maxlen) {
maxlen = num[i][j];
// generate substring from str1 => i
int thisSubsBegin = i - num[i][j] + 1;
if (lastSubsBegin == thisSubsBegin) {
//if the current LCS is the same as the last time this block ran
sb.append(str1.charAt(i));
} else {
//this block resets the string builder if a different LCS is found
lastSubsBegin = thisSubsBegin;
sb = new StringBuilder();
sb.append(str1.substring(lastSubsBegin, i + 1));
}
}
}
}
}
return sb.toString();
}
So, my function should looks like:
public static String longestSubstring(String str1, String str2, String[] ignore)
Create a suffix tree of one of your strings and run through the second to see which substring can be found in the suffix tree.
Info on suffixtrees: http://en.wikipedia.org/wiki/Suffixtree
As far as I understand, you have to ignore those substrings that contain at least one string from ignore.
if (str1.charAt(i) == str2.charAt(j)) {
if ((i == 0) || (j == 0)) {
num[i][j] = 1;
} else {
num[i][j] = 1 + num[i - 1][j - 1];
}
// we must update `sb` on every step so that we can compare it with `ignore`
int thisSubsBegin = i - num[i][j] + 1;
if (lastSubsBegin == thisSubsBegin) {
sb.append(str1.charAt(i));
} else {
lastSubsBegin = thisSubsBegin;
sb = new StringBuilder();
sb.append(str1.substring(lastSubsBegin, i + 1));
}
// check whether current substring contains any string from `ignore`,
// and if it does, find the longest one
int biggestIndex = -1;
for (String s : ignore) {
int startIndex = sb.lastIndexOf(s);
if (startIndex > biggestIndex) {
biggestIndex = startIndex;
}
}
//Then sb.substring(biggestIndex + 1) will not contain strings to be ignored
sb = sb.substring(biggestIndex + 1);
num[i][j] -= (biggestIndex + 1);
if (num[i][j] > maxlen) {
maxlen = num[i][j];
}
}
If you have to ignore those substrings that are exactly the same as any string in ignore,
then when the candidate for longest common substring is found, iterate over ignore and check whether there is current substring in it.