How to merge two String into one String in java - java

Suppose:
String s1="13579";
String s2="2468";
then output would be 123456789
Here my code :
public class JoinString {
public static void main(String[] args) {
String s1 = "13579";
String s2 = "2468";
for (int i = 0; i < s1.length(); i++) {
for (int j = i; j < s2.length(); j++) {
System.out.print(s1.charAt(i) + "" + s2.charAt(j));
break;
}
}
}
}

StringBuilder buf = new StringBuilder();
for (int i = 0; i < Math.max(s1.length(), s2.length()); i++) {
if (i < s1.length()) {
buf.append(s1.charAt(i));
}
if (i < s2.length()) {
buf.append(s2.charAt(i));
}
}
final String result = buf.toString();
You only need one loop. Also, you can use a StringBuilder class to build your string character by character.

How about this little trick:
String s1 = "13579";
String s2 = "2468";
String s3 = (s1 + s2).codePoints() // stream of code points
.sorted()
// collect into StringBuilder
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
System.out.println(s3); // 123456789

A simple way to achieve that is by doing something like this:
String s1 = "13579";
String s2 = "2468";
char[]result = (s1+s2).toCharArray();
Arrays.sort(result);
System.out.println(result);
Output:
123456789

You just need to combine the logic of the two loops like this (and use StringBuilder if you want to build a string this way).
String s1 = "13579";
String s2 = "2468";
int length = Math.max(s1.length(), s2.length());
for (int i = 0; i < length; i++) {
if(i < s1.length())
System.out.print(s1.charAt(i));
if(i < s2.length())
System.out.print(s2.charAt(i));
}

Similar to #Roman Puchovskiy, here is a way to do it without the StringBuilder.
String s1 = "abcde";
String s2 = "defgh";
String combined = "";
int length = s1.length() > s2.length() ? s1.length() : s2.length(); //Finds the longest length of the two, to ensure no chars go missing
for(int i = 0 ; i < length ; i++) {
if(i < s1.length()) { // Make sure there is a char in s1 where we're looking.
combined += s1.charAt(i);
}
if(i < s2.length()) { // Same with s2.
combined += s2.charAt(i);
}
}
Where combined becomes the combined string. ("adbecfdgeh").
Hope this helps!

Similar way as merge method in merge sort.
Also it's better if you convert string to char array so that random access to element is in constant time.
Because charAt has O(n) time complexity.
public class JoinString {
public static void main( String[] args ) {
String s1 = "13579";
String s2 = "2468";
final char[] str1 = s1.toCharArray();
final char[] str2 = s2.toCharArray();
int i;
for ( i = 0; i < str1.length && i < str2.length; i++ ) {
System.out.print( str1[i] + "" + str2[i] );
}
while ( i < str1.length ) {
System.out.print( str1[i] + "" );
i++;
}
while ( i < str2.length ) {
System.out.print( str2[i] + "" );
i++;
}
}
}

Related

Getting String and return the same string with "+" before every"-"

I get a String and I need to return with "+" before every "-"in it
for example for the String= "5x^6+3x-8x^2-8x^3" it should return:5x^6+3x+-8x^2+-8x^3
String p="-5.0x^4-1.0x^3-3.0x^2-2.0"
String temp=p;
for(int i = 1;i<p.length();i++) {
int start=0;
if(p.charAt(i)=='-') {
temp =temp.substring(start,i);
temp+="+";
temp+=p.substring(i+1,p.length());//here it over writes
start=i;
}
}
it switches the "-" with "+"
the return: -5.0x^4+1.0x^3+3.0x^2+2.0
Instead of concatentating substrings, I would use a StringBuilder. Iterate the contents. On - insert a +. Like,
String p = "5x^6+3x-8x^2-8x^3";
StringBuilder sb = new StringBuilder(p);
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == '-') {
sb.insert(i, '+');
i++;
}
}
p = sb.toString();
Results in (as requested)
5x^6+3x+-8x^2+-8x^3

How to compute all the possible permutations given the characters of a given string?

I have written this code to find the possible permutation of string using iterative approach, but it's giving wrong output as follows. Please advise, what's wrong in the code?
Output I'm getting:
BCAABC ACBABC ABCABC
Expetced output is :
ABC ACB BAC BCA CBA CAB
public class PrintPermutation {
public static void main(String[] args) throws Exception {
String str = "ABC";
String permutation = str + "";
if (str.length() == 0) {
System.out.println("String length is zero and can't make the permutation");
return;
}
for (int i = 0; i < str.length(); i++)
{
char ch = str.charAt(i);
String left = str.substring(0, i);
String right = str.substring(i + 1);
String Merge = left + right;
System.out.println(Merge+ch+permutation);
}
}
}
This is a solution I found online. This one is interesting, because rather than using recursion or some complex iterative algorithm, they make the solution simpler by using some mathematical understanding. link here
public static void permutateString2(String s){
int len = s.length();
int factorial = factorial(s.length());
for (int i=0; i<factorial; i++){
String str = s;
int counter = 0;
StringBuilder permutation = new StringBuilder();
while (counter < len){
int idx = i % (len - counter);
permutation.append(str.charAt(idx));
if (idx == 0){
str = str.substring(idx+1);
}else if (idx == str.length()-1){
str = str.substring(0, str.length()-1);
}else{
str = str.substring(0, idx) + str.substring(idx+1, str.length());
}
counter++;
}
System.out.println(permutation.toString());
}
}
private static int factorial(int n){
int result = 1;
for (int i=1; i<= n; i++){
result *= i;
}
return result;
}

How to ignore spaces while Sorting a string in java?

I tried to code a program to detect an anagram with 2 Strings given.
My approach is to convert both strings to char Arrays and then sort them before comparing them.
I know I could use the sort() function but I don't want to use any imports for training purposes.
The problem is i want my programm to ignore blanks while scanning for an anagram.
in the current version the ouput is like this:
(triangle, relating) ---> true
(tri angle, relating) ---> false
while it should be both true.
i would be thankful for any help!
heres my code, (please ignore my comments):
public static boolean anagramCheck(String a, String b) {
boolean r = true;
// In Char Arrays umwandeln /
char[] Ca = a.toCharArray();
char[] Cb = b.toCharArray();
// Laengen Abfrage
int L1 = Ca.length;
int L2 = Cb.length;
// Erste For-Schleife
for (int i = 0; i < L1; i++) {
for (int j = i + 1; j < L1; j++) {
if (Ca[j] < Ca[i]) {
char temp = Ca[i];
Ca[i] = Ca[j];
Ca[j] = temp;
}
}
}
// Zweite For-schleife
for (int i = 0; i < L2; i++) {
for (int j = i + 1; j < L2; j++) {
if (Cb[j] < Cb[i]) {
char temp = Cb[i];
Cb[i] = Cb[j];
Cb[j] = temp;
}
}
}
// Char Arrays zu Strings
String S1 = String.valueOf(Ca);
String S2 = String.valueOf(Cb);
// Vergleich und Ausgabe
if (S1.compareTo(S2) == 0) {
return r;
}
else {
r = false;
return r;
}
}
}
The String.replace(String, String) is the non-regexp replace method.
So remove all spaces:
String S1 = String.valueOf(Ca).replace(" ", "");
String S2 = String.valueOf(Cb).replace(" ", "");
It would be nicer to do this on a and b.
public static boolean isAnagram(String one, String two) {
char[] letters = new char[26];
for (int i = 0; i < one.length(); i++) {
char ch = Character.toLowerCase(one.charAt(i));
if (Character.isLetter(ch))
letters[ch - 'a']++;
}
for (int i = 0; i < two.length(); i++) {
char ch = Character.toLowerCase(two.charAt(i));
if (Character.isLetter(ch))
letters[ch - 'a']--;
}
for (int i = 0; i < letters.length; i++)
if (letters[i] != 0)
return false;
return true;
}
Generally, less code is better (if it’s readable). And learning a language means learning the built in libraries.
Here’s a method to return a String of sorted chars:
public static String sortChars(String str) {
return str.replace(" ", "").chars().sorted()
.mapToObj(c -> (char)c + "")
.collect(Collectors.joining(""));
}
With this method, your main method becomes:
public static boolean anagramCheck(String a, String b) {
return sortedChars(a).equals(sortedChars(b));
}
Refactoring like this, using well-named methods makes your code easier to understand, test, debug and maintain.
It’s worth noting that you don’t actually need a sorted String… a sorted array would serve equally well, and requires less code:
public static int[] sortChars(String str) {
return str.replace(" ", "").chars().sorted().toArray();
}
public static boolean anagramCheck(String a, String b) {
return Arrays.equal(sortedChars(a), sortedChars(b));
}
A frequency map could be created with the characters from String one incrementing and the characters from String two decrementing, then the resulting map should contain only 0 as values.
To skip non-letters, Character::isLetter can be used.
public static boolean isAnagram(String a, String b) {
Map<Character, Integer> frequencies = new HashMap<>();
for (int i = 0, na = a.length(), nb = b.length(), n = Math.max(na, nb); i < n; i++) {
if (i < na && Character.isLetter(a.charAt(i)))
frequencies.merge(Character.toLowerCase(a.charAt(i)), 1, Integer::sum);
if (i < nb && Character.isLetter(b.charAt(i)))
frequencies.merge(Character.toLowerCase(b.charAt(i)), -1, Integer::sum);
}
return frequencies.values().stream().allMatch(x -> x == 0);
}

how to split a string by using charAt and string.length()

only allow charAt method and length method . Thank you so much!
void runApp() {
String str = "345, 688"; //->"345" "688"
String value = strCut(str);
}
String strCut(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(3) == ',') {
what should i write here ? ?
}
Your code needs some refactoring, try this:
void runApp() {
String str = "345, 688"; //->"345" "688"
String value = strCut(str);
}
String strCut(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
int cutStringIndex;
if (str.charAt(i) == ',') {
cutStringIndex = i;
}
for (int i = 0; i < cutStringIndex(); i++) {
String cutStringOne = "";
cutStringOne = cutStringOne + str.charAt(i);
}
for (int i = cutStringIndex() + 1; i < str.length(); i++) {
String cutStringTwo = "";
cutStringTwo = cutStringTwo + str.charAt(i);
}
cutString = cutStringOne + " " + cutStringTwo;
return cutString;
}
This will take out the comma which appears to be what you were looking for. I only used the two methods you asked for. Essentially this code gets the index of the comma, then reconstructs the two parts of the strings until it reaches the point of the comma, and skips over it. It may need some minor tweaks for your situation but this should be what you're looking for.
It can be done like this, Suppose String s="200,300,450,600" and you have to split given string using charAt() and string.length() method then first add ',' at the end of the string as given in the code below.
String s="200,300,450,600,",str="";
for(int i=0;i<s.length();i++){
char ch=s.charAt(i);
if(ch!=','){ //checking if particular character is not ','
str+=ch; //storing it in str string
}
else{
System.out.println(str); //printing each string before ',' is found
str="";
}
}
The output of above code will be:200
300
450
600(all the numbers will be printed on next line)
If you want to use only charAt and string.length() then you should try this
void runApp{
String str = "345, 688, 123";
String values[] = strCut(str); //values[0] = 345, values[1] = 688, values[2] = 123
for(String value : values){
System.out.print(value + " ");
}
}
String[] strCut(String str) {
int elements = 1;
int index = 0;
for(int i = 0; i < str.length(); i++){
if(str.charAt(i) == ',')
elements++;
}
String result[] = new String[elements];
for(int i = 0; i < result.length; i++)
result[i] = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != ',') {
if(str.charAt(i) != ' ')
result[index] = result[index] + str.charAt(i);
}
else index++;
}
return result;
}
You can do it as follows:
public class Main {
public static void main(String[] args) {
// Test
runApp();
}
static void runApp() {
String str = "345, 688"; // Expected->"345" "688"
String value = strCut(str);
System.out.println(value);// Display the result
}
static String strCut(String str) {
// Initialise result with a "
String result = "\"";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',') {// Check char at the index, i
// Add " at the end of one number and again " at the start of the next
result += "\" \"";
} else if (str.charAt(i) != ' ') {
result += str.charAt(i);
}
}
// Add " at the end
result += "\"";
// Finally, return result
return result;
}
}
Output:
"345" "688"
if you must want to make use of charAt() then do like below..
ArrayList<String> stringArr= new ArrayList<String>();
int startindex=0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == ',')
{
String partString = str.substring(startindex, i) ;
startindex=i+1;
stringArr.add(partString);
}
}
String lastString = str.substring(startindex, str.length()) ;
stringArr.add(lastString);
OR
You can simply use split method like below
String[] parts = string.split(",");
String part1 = parts[0]; // 345
String part2 = parts[1]; // 688
You can achieve it by simply doing this,
This will give you the desired result.
String str = "345,688";
ArrayList<String> stringArray = new ArrayList<>();
int startindex=0;
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) == ',') {
String subStr = str.substring(startindex, i);
startindex = i+1;
stringArray.add(subStr);
}
}
stringArray.add(str.substring(startindex));

Fancy looping in Java

I have a problem wherein I have two strings, the length of one of which I will know only upon execution of my function. I want to write my function such that it would take these two stings and based upon which one is longer, compute a final string as under -
finalString = longerStringChars1AND2
+ shorterStringChar1
+ longerStringChars3and4
+ shorterStringChar2
+ longerStringChars5AND6
...and so on till the time the SHORTER STRING ENDS.
Once the shorter string ends, I want to append the remaining characters of the longer string to the final string, and exit. I have written some code, but there is too much looping for my liking. Any suggestions?
Here is the code I wrote - very basic -
public static byte [] generateStringToConvert(String a, String b){
(String b's length is always known to be 14.)
StringBuffer stringToConvert = new StringBuffer();
int longer = (a.length()>14) ? a.length() : 14;
int shorter = (longer > 14) ? 14 : a.length();
int iteratorForLonger = 0;
int iteratorForShorter = 0;
while(iteratorForLonger < longer) {
int count = 2;
while(count>0){
stringToConvert.append(b.charAt(iteratorForLonger));
iteratorForLonger++;
count--;
}
if(iteratorForShorter < shorter && iteratorForLonger >= longer){
iteratorForLonger = 0;
}
if(iteratorForShorter<shorter){
stringToConvert.append(a.charAt(iteratorForShorter));
iteratorForShorter++;
}
else{
break;
}
}
if(stringToConvert.length()<32 | iteratorForLonger<b.length()){
String remainingString = b.substring(iteratorForLonger);
stringToConvert.append(remainingString);
}
System.out.println(stringToConvert);
return stringToConvert.toString().getBytes();
}
You can use StringBuilder to achieve this. Please find below source code.
public static void main(String[] args) throws InterruptedException {
int MAX_ALLOWED_LENGTH = 14;
String str1 = "yyyyyyyyyyyyyyyy";
String str2 = "xxxxxx";
StringBuilder builder = new StringBuilder(MAX_ALLOWED_LENGTH);
builder.append(str1);
char[] shortChar = str2.toCharArray();
int index = 2;
for (int charCount = 0; charCount < shortChar.length;) {
if (index < builder.length()) {
// insert 1 character from short string to long string
builder.insert(index, shortChar, charCount, 1);
}
// 2+1 as insertion index is increased after after insertion
index = index + 3;
charCount = charCount + 1;
}
String trimmedString = builder.substring(0, MAX_ALLOWED_LENGTH);
System.out.println(trimmedString);
}
Output
yyxyyxyyxyyxyy
String one = "longwordorsomething";
String two = "short";
String shortString = "";
String longString = "";
if(one.length() > two.length()) {
shortString = two;
longString = one;
} else {
shortString = one;
longString = two;
}
StringBuilder newString = new StringBuilder();
int j = 0;
for(int i = 0; i < shortString.length(); i++) {
if((j + 2) < longString.length()) {
newString.append(longString.substring(j, j + 2));
j += 2;
}
newString.append(shortString.substring(i, i + 1));
}
// Append last part
newString.append(longString.substring(j));
System.out.println(newString);

Categories

Resources