How to convert an array of bits into text - java

I had a string for eg "java education" which I have converted into bits. Now I have an array of bits. I want to convert it back into text. How to do this?
String s="Java Education";
char[] ch=s.toCharArray();
String g=" ";
StringBuilder sb= new StringBuilder();
for(char c:ch)
{
g=Integer.toBinaryString((int)c);
sb.append(ch);
}
char[] ch2= sb.toString.toCharArray();
I want to get back the text from the array ch2.

Try this
import java.util.Arrays;
public class DecodeBits {
public static void main(String[] args) {
String s = "Java Education";
char[] ch = s.toCharArray();
StringBuilder sb = new StringBuilder();
for (char c : ch) {
// Wen need a fix length
String g = String.format("%16s", Integer.toBinaryString((int) c)).replace(' ', '0');
// this seems to be typo
// sb.append(ch);
sb.append(g);
}
char[] ch2 = sb.toString().toCharArray();
int start = 0;
while (start < ch2.length - 15) {
char[] bits = Arrays.copyOfRange(ch2, start, start + 16);
int cValue = Integer.parseInt(new String(bits), 2);
char[] chars = Character.toChars(cValue);
System.out.print(chars[0]);
start += 16;
}
System.out.println("");
}
}

Here is my implementation:
String s="Java Education";
char[] ch=s.toCharArray();
String g="";
StringBuilder sb= new StringBuilder();
for(char c:ch)
{
g=Integer.toBinaryString((int)c);
if(g.length()<8){
for(int h=0; h<8-g.length(); h++){
g="0"+g;
}
}
sb.append(g);
sb.append(',');
}
char[] ch2= sb.toString().toCharArray();
String[] s3 = new String(ch2).split(",");
for(String t: s3){
String d="";
for(int x=t.length()-1; x>=0; x--) d+=t.charAt(x);
t=d;
int num=0;
for(int j=0; j<t.length(); j++){
num+=Integer.parseInt(""+t.charAt(j))*Math.pow(2, j);
}
System.out.print((char)num);
}

Related

Removing all the characters from a given string

how can I modify my code so that it removes all the characters in a given string (not just a string) in another string in O(n)? If using other data structures would help, please hint as well.
public static String removeChar(String s, char ch){
StringBuilder sb= new StringBuilder();
char[] charArray= s.toCharArray();
for (int i=0; i<charArray.length; i++){
if (charArray[i]!=ch) {
sb.append(charArray[i]);
}
}
return sb.toString();
}
Is there a faster way for this?
UPDATE: I want to write a new function like removeAllCharsInSecondStringFromFirstString(String S1, String S2)
Rather then iterating each character of the String, you could use String.indexOf(int) and a loop to add each substring between ch intervals. Something like,
public static String removeChar(String s, char ch) {
StringBuilder sb = new StringBuilder();
int p1 = 0, p2 = s.indexOf(ch);
while (p2 > -1) {
sb.append(s.substring(p1, p2));
p1 = p2 + 1;
p2 = s.indexOf(ch, p1);
}
if (p1 < s.length()) {
sb.append(s.substring(p1, s.length()));
}
return sb.toString();
}
With hints and help of dimo I wrote this solution:
public static String removeAllChars(String src, String dst){
HashSet<Character> chars = new HashSet<>();
char[] dstCharArray=dst.toCharArray();
for (int i=0; i<dstCharArray.length; i++){
chars.add(dstCharArray[i]);
}
StringBuilder sb = new StringBuilder();
char[] srcCharArray = src.toCharArray();
for (int i=0; i<srcCharArray.length; i++){
if (!chars.contains(srcCharArray[i])){
sb.append(srcCharArray[i]);
}
}
return sb.toString();
}
If you really want to implement this yourself you can use a Set to contain the collection of characters that you want to strip out. Here's a template to get you started:
public static String removeAllChars(String source, String charsString) {
HashSet<Character> chars = new HashSet<>();
for (int i = 0; i < charsString.length(); i++) {
chars.add(charsString.charAt(i));
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < source.length(); i++) {
// chars.contains(source.charAt(i)) is O(1)
// use this to determine which chars to exclude
}
return sb.toString();
}
Try to use this.
Remove all no numerical value
String str = "343.dfsdgdffsggdfg333";
str = str.replaceAll("[^\\d.]", "");
Output will give you "343.333"
If in the future you will need delete numerical and special value try this
String str = "343.dfsdgdffsggdfg333";
string = string.replace(/[^a-zA-Z0-9]/g, '');

Reversing the characters of each individual word of a sentence without reversing the word order

I have this code that is supposed to do what the title said, reverse the order of characters without changing the order of the words:
package stackTests;
import java.util.Scanner;
import java.util.Stack;
public class StackTest
{
Stack<Character> stack;
public StackTest()
{
stack = new Stack<Character>();
}
public String reverseString(String str)
{
int start = 0;
int start2 = 0;
int size;
char space = ' ';
char[] cArr;
Scanner scan = new Scanner(str);
cArr = str.toCharArray();
for (; start < cArr.length; start++)
{
if(cArr[start] == space || start == cArr.length - 1)
{
for (; start2 < stack.size(); start++)
{
System.out.print(stack.pop());
}
}
else
{
stack.push(cArr[start]);
}
start2 = 0;
}
return str;
}
}
It works fine if I enter a single word like "Hello"--it will output "olleH"--but as soon as it gets more complicated than one word it starts to output some weird things."Hello my name is" outputs "ollehem". I'm really new to Stacks and this is my first time using them. I'm not sure if there is a logic error or improper use of Stacks.
you're not outputting original spaces, this is why you're seeing strange results
here is fixed version:
public static void reverseString(final String str) {
final Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
final char c = str.charAt(i);
if (c == ' ') {
while (!stack.isEmpty())
System.out.print(stack.pop());
System.out.print(' ');
} else
stack.push(c);
}
while (!stack.isEmpty())
System.out.print(stack.pop());
}
another version without stack, with in-place replacement:
public static void reverseString(final String str) {
final char[] chars = str.toCharArray();
int start = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == ' ') {
reverse(chars, start, i - 1);
start = i + 1;
}
}
reverse(chars, start, chars.length - 1);
System.out.println(new String(chars));
}
private static void reverse(final char[] chars, int s, int e) {
while (s < e) {
final char t = chars[s];
chars[s] = chars[e];
chars[e] = t;
s++;
e--;
}
}
If you HAVE to use a stack, I would follow an algorithm like this:
String myString = "Hello World";
Stack<Character> stack = new Stack<Character>();
StringBuilder sb = new StringBuilder();
String[] splitString = myString.split(" ");
//Iterate through each word in the string
for(String s : splitString){
//Push each character of the word into LIFO stack
for(char c : s.toCharArray()){
stack.push(c);
}
//Build new string with reverse ordered characters
while(!stack.isEmpty()){
sb.append(stack.pop());
}
//Append a space as long as it's not the last word of the original string
if(!s.equals(splitString[splitString.length - 1]))
sb.append(" ");
}
//Print the new string
System.out.println(sb.toString());
I'm not sure efficiency matters to you, but this algorithm would work in linear time, where n is the number of characters in the string.
Here is how you can do it in-place without using any extra space (Not using stack):
public class ReverseWordsInplace {
public static void main(String[] args) {
reverseWords(new StringBuilder("This is a test"));
}
public static void reverseWords(StringBuilder s) {
StringBuilder str = new StringBuilder(s);
int startWordIndex = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ' || str.length() - 1 == i) {
int x = 0;
int endWordIndex = str.charAt(i) == ' ' ? i - 1 : i;
while (endWordIndex - x > startWordIndex + x) {
char c1 = str.charAt(startWordIndex + x);
char c2 = str.charAt(endWordIndex - x);
str.setCharAt(startWordIndex + x, c2);
str.setCharAt(endWordIndex - x, c1);
x++;
}
startWordIndex = i + 1;
}
}
System.out.println(str);
}
}
Output:
sihT si a tset

How to remove repeated letter from words in Java

i have problem writing java code to remove repeated letters from word.This code will remove repeated letter by accepting only one of the letter which is repeating . Suppose, if input is "SUSHIL" then output would be "SUHIL".
This java code i write.
import java.io.*;
import java.util.*;
public class Repeat
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
char ch1, ch2;
int i, j;
int l = name.length();
String result = "";
for (i = 0; i < l; i++)
{
for (j = 1; j < l; j++)
{
ch1 = name.charAt(i);
ch2 = name.charAt(j);
if (ch1 != ch2)
{
result = result + ch1;
break;
}
}
}
System.out.println("Output:" + result);
}
}
try this:
private static String removeRepeat(String input){
Set<Character> str = new LinkedHashSet<Character>();
for(int n=0;n<input.length();n++){
str.add(input.charAt(n));
}
return str.toString();
}
good point from the comment, changed to LinkedHashSet.
It may be the crap code, but what I mean is don't reinvent the wheel, only if you have to
char ch1,ch2;
int l=name.length();
String result="";
for(int i=0;i<l;i++){
if(name.indexOf(name.charAt(i))==i){
result+=name.charAt(i);
}
}
System.out.println(result);
input = SUSHSILHI
output = SUHIL
You should do the opposite: add the first letter to result, then check if the next letter is already in result:
boolean exist=false;
result=name.charAt(0);
for (i=1; i<l;i++) {
exist=false;
int j=0;
while (exist=false && j<i) {
if(name.charAt(i)==charAt(j)) {
exist=true;
}
j++;
}
if(exist==false){
result=result+name.charAt(i);
}
}
The for checks for all the string name, then the while checks for the characters already in result, if it doesn't already exist, else it doesn't do anything.
Using indexOf() , one for loop should work, like below
String name="SUSHIL";
String newName="";
int i=0;
int l=name.length();
for(i=0;i<l;i++)
{
char ch1=name.charAt(i);
if(!(newName.indexOf(ch1)>-1))
{
newName=newName + ch1;
}
}
System.out.println("Output:"+newName);
String name = "SUSHIL";
char ch1 = 0, ch2;
int i, j;
int l = name.length();
StringBuilder sb = new StringBuilder();
for (i = 0; i < l; i++)
{
//this is used to append char to StringBuilder
boolean shouldAppend = true;
//if we don't check if the length is equal to 0 to start then the below loop will never run and the result would be an empty string so just append the first character to the StringBuilder
if (sb.length() == 0)
{
sb.append(name.charAt(i));
shouldAppend = false;
}
else
{
for (j = 0; j < sb.length(); j++)
{
ch1 = name.charAt(i);
ch2 = sb.charAt(j);
if (ch1 == ch2)
{
//StringBuilder contains ch1 so turn shouldAppend to false and break out of this inner loop
shouldAppend = false;
break;
}
}
}
if (shouldAppend) sb.append(ch1);
}
System.out.println("Output:" + sb.toString());
Try:
//Globally
List<Character> list = new ArrayList<Character>();
public String remRepeats(String original)
{
char ch = original.charAt(0);
if (original.length() == 1)
return original;
if (list.contains(ch))
return remRepeats(original.substring(1));
else
{
list.add(ch);
return ch + remRepeats(original.substring(1));
}
}
List<Character> characters = new ArrayList<>();
char[] chars = name.toCharArray();
StringBuilder stringBuilder = new StringBuilder();
for(char currChar:chars) {
if (!characters.contains(currChar)) {
characters.add(currChar);
stringBuilder.append(currChar);
}
}
System.out.println(stringBuilder);

Converting \n to String without \\n

How can I convert "\n" into a char[]? I want to do this because I want to do some string manipulation when \n is entered in the method as input. I know that if \\n is entered then the output will be \n as a string. I want to implement a method to take in input as \n not \\n to get the string result.
tests:
char[] arr = new char[2];
String str = "\n";
arr = str.toCharArray();
System.out.println(arr.length);
for (char c : arr) {
System.out.println(c);
}
ouput:
1
// newline empty space
my reverse string method
public static String reverseStr(String str) {
if ( str == null ) {
return null;
}
int len = str.length();
if (len <= 0) {
return "";
}
char[] strArr = new char[len];
int count = 0;
for (int i = len - 1; i >= 0; i--) {
strArr[count] = str.charAt(i);
count++;
}
return new String(strArr);
}
newlines are represented as 10 in ascii. you can try this.
char[] arr = new char[3];
int str = 10;
arr[0] = 'a';
arr[1] = (char)str;
arr[2] = 'c';
System.out.println(arr.length);
for (char c : arr) {
System.out.println(c);
}
One way to do it is by using Stringbuilder
String builder(StringBuilder has overloaded methods for char and Sting).
StringBuilder str= new StringBuilder();
str.append('\n'); or
str.append("\n");

Array of Characters

The Following method receives an array of Character objects and returns a new array with only characters that are digits.
Example;
old[] array:{1,R,Y,O,2,3,3 }----new [] array: {1,2,3,3}.
This is my code, and it is not returning what I want it to return.
public static char[] getDigits(char[] charArray) {
I think you need to do two loops to size your array correctly.
public static char[] getDigits(char[] charArray) {
int digitCount = 0;
for (char ch : charArray) {
if (Character.isDigit(ch)) {
digitCount++;
}
}
char[] toReturnDigits = new char[digitCount];
int index = 0;
for (char ch : charArray) {
if (Character.isDigit(ch)) {
toReturnDigits[index++] = ch;
}
}
return toReturnDigits;
}
public static char[] getDigitsOld(char[] charArray) {
int arrayLength = charArray.length;
char[] toReturnDigits = new char[arrayLength];
int index = 0;
for (int i = 0; i < arrayLength; i++) {
if (charArray[i] >= 48 && charArray[i] <= 57) {
toReturnDigits[index++] = charArray[i];
}
}
return toReturnDigits;
}
public static void main(String arg[]) {
char[] old = new char[] { '1', 'R', 'Y', 'O', '2',
'3', '3' };
System.out.println(Arrays
.toString(getDigitsOld(old)));
System.out.println(Arrays
.toString(getDigits(old)));
}
Outputs
[1, 2, 3, 3,
[1, 2, 3, 3]
Why not just checking if is a number?:
public static char[] getDigits(char[] charArray) {
int arrayLength = charArray.length;
char[] toReturnDigits = new char[arrayLength];
int index = 0;
for (int i = 0; i < arrayLength; i++) {
if (parseInt(charArray[i].toString(), 10)) { //assuming you expect base 10 digits
toReturnDigits[index++] = charArray[i];
}
}
return toReturnDigits;
}
EDIT: To solve the issue with the array length you could use a dynamic array instead of preallocating it:
...
var toReturnDigits = [];
for (int i = 0; i < arrayLength; i++) {
if (parseInt(charArray[i].toString(), 10)) { //assuming you expect base 10 digits
toReturnDigits.push(charArray[i]);
}
}
return toReturnDigits;
If you want to array to just contain the digits, you either have to count the number of digits before you create the array or use a list.
P.S. You should prefer to use Character.isDigit(char) as opposed to comparing.
Perhaps you could try something like:
public static char[] getDigits(final char[] array){
final StringBuilder builder = new StringBuilder();
for(final char c : array)
if(Character.isDigit(c))
builder.append(c);
return builder.toString().toCharArray();
}
You can do this using regex easily.
public static char[] getDigits(char[] charArray) {
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(String.valueOf(charArray));
String str=new String();
while (m.find()) {
str=str+m.group();
}
return str.toCharArray();
}
Demo
Again you can do this easy in following way too.
public static char[] getDigits(char[] charArray) {
String str=new String();
for(int i=0;i<charArray.length;i++){
if(Character.isDigit(charArray[i])){
str=str+charArray[i];
}
}
return str.toCharArray();
}

Categories

Resources