Java Program to format the string (having only 1 and 0) in such a way that all 1s should be printed first then all 0s
for example the string 0011010101010001 should be printed as 0000000001111111
/* Method 1*/
package dev21century;
public class StringPattern3 {
public static void main(String[] args) {
String str = "0011010101010001";
char[] strAsCharArray = str.toCharArray();
int index1 = str.length() - 1;
int index2 = 0;
for (int i = 0; i < str.length(); i++) {
char tempChar = str.charAt(i);
if (tempChar == '1') {
strAsCharArray[index1] = tempChar;
index1--;
}
if (tempChar == '0') {
strAsCharArray[index2] = tempChar;
index2++;
}
}
System.out.println(strAsCharArray);
}
}
/* Method 2*/
package dev21century;
public class StringPattern3 {
public static void main(String[] args) {
String str = "0011010101010001";
StringBuffer tempStr1 = new StringBuffer();
StringBuffer tempStr2 = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char tempChar = str.charAt(i);
if (tempChar == '1')
tempStr1.append(tempChar);
if (tempChar == '0')
tempStr2.append(tempChar);
}
str = tempStr1.toString() + tempStr2.toString();
System.out.println(str);
}
}
for example the string 0011010101010001 should be printed as 0000000001111111
/* Method 1*/
package dev21century;
public class StringPattern3 {
public static void main(String[] args) {
String str = "0011010101010001";
char[] strAsCharArray = str.toCharArray();
int index1 = str.length() - 1;
int index2 = 0;
for (int i = 0; i < str.length(); i++) {
char tempChar = str.charAt(i);
if (tempChar == '1') {
strAsCharArray[index1] = tempChar;
index1--;
}
if (tempChar == '0') {
strAsCharArray[index2] = tempChar;
index2++;
}
}
System.out.println(strAsCharArray);
}
}
/* Method 2*/
package dev21century;
public class StringPattern3 {
public static void main(String[] args) {
String str = "0011010101010001";
StringBuffer tempStr1 = new StringBuffer();
StringBuffer tempStr2 = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char tempChar = str.charAt(i);
if (tempChar == '1')
tempStr1.append(tempChar);
if (tempChar == '0')
tempStr2.append(tempChar);
}
str = tempStr1.toString() + tempStr2.toString();
System.out.println(str);
}
}
Output for both programs:
1111111000000000
No comments:
Post a Comment