Converting String to it's integer ascii values - java

I'm stuck at the very end of my problem getting a NumberFormatException.
I want to take a string such as Wsup, and turn it into its ASCII values with the result, '87115117112'.
I've gotten that string of numbers built successfully a couple different ways, but when I try to parseInt(string) on it, I get my exception. I've tried printing out the string as an array of characters to look for hidden white space, I've used String.trim() with no luck, I'm quite confused why it isn't recognized as a valid integer.
public static int toAscii(String s){
StringBuilder sb = new StringBuilder();
String ascString = null;
long asciiInt;
for (int i = 0; i < s.length(); i++){
sb.append((int)s.charAt(i));
char c = s.charAt(i);
}
ascString = sb.toString();
asciiInt = Integer.parseInt(ascString); // Exception here
return 0;// asciiInt; 0 in place just to run
}
Thanks for any help given.

Yor asciiInt is long type so do it in this way
asciiInt = Long.parseLong(ascString);
here is your full function
public static long toAscii(String s){
StringBuilder sb = new StringBuilder();
String ascString = null;
long asciiInt;
for (int i = 0; i < s.length(); i++){
sb.append((int)s.charAt(i));
char c = s.charAt(i);
}
ascString = sb.toString();
asciiInt = Long.parseLong(ascString);
return asciiInt;
}

You need to return as long not as integer I have implement your toAscii() with little bit
public static long toAscii(String s){
StringBuilder sb = new StringBuilder();
long asciiInt;
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
asciiInt = (int)c;
System.out.println(c +"="+asciiInt);
sb.append(asciiInt);
}
return Long.parseLong(sb.toString());
}

Related

Java pword-generator does not update random inside loop

Im working on an assignment for school where i am going to finish a short password generator.
when trying to loop adding characters out of the string, it ends up adding the same character, but if i would just print out characters it gives different ones. could someone explain why this is? i would really like to learn.
private void program() {
System.out.println(generate(all));
}
Random rand = new Random();
String all = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int randomInt = rand.nextInt(all.length());
char randomchar = all.charAt(randomInt);
StringBuilder sb = new StringBuilder();
String generate (String string) {
while (sb.length() < 10) {
sb.append(randomchar);
}
return sb.toString();
}
}
You are setting nextInt and nextChar gloabally. This need to be moved to your generation method.
String generate (String string) {
StringBuilder sb = new StringBuilder();
while (sb.length() < 10) {
int randomInt = rand.nextInt(all.length());
char randomchar = all.charAt(randomInt);
sb.append(randomchar);
}
return sb.toString();
}
Size your StringBuilder for efficiency (and big passwords)
public String generatePassword(String candidateChars, int passwordLength) {
Random rand = new Random();
int max = candidateChars.length();
StringBuilder sb = new StringBuilder(passwordLength);
for (int i = 0; i < passwordLength; i++) {
char randomchar = candidateChars.charAt(rand.nextInt(max));
sb.append(randomchar);
}
return sb.toString();
}
You should (re-)generate randomInt as well as randomchar within loop:
while (sb.length() < 10) {
// we want fresh value on ach itteration
int randomInt = rand.nextInt(all.length());
char randomchar = all.charAt(randomInt);
sb.append(randomchar);
}

Binary addition of Strings

I need to combine an array of strings as below ( so as each character in the result string is a bitwise & of the characters in the input string)
String a = "10110001"
String b = "01101101"
String c = "10101011"
String result = "00100001"
Solution I came up with:
long resultLong = 0;
for( String a : inputs )
{
resultLong = resultLong & Long.parseLong( a ,2);
}
String result = Long.toBinaryString( resultLong );
The number of characters in the input string could be very long, and the above solution wouldn't work (NumberFormatException) . I couldn't get my head around how to implement this, what would be the cleanest way ?
If Long is not enough for your use case then you can use BigInteger
BigInteger(String val, int radix);
Which takes a String and radix as the arguments.
BigInteger result = new BigInteger(inputs[0], 2);
for (int i = 1; i < inputs.length; i++) {
result = result.and(new BigInteger(inputs[i], 2));
}
String resultStr = result.toString(2);
Here's your algorithm. This will work for any number of Strings provided that all the Strings are of same length:
public static void main(String[] args) {
String a = "10110001";
String b = "01101101";
String c = "10101011";
String arr[] = new String[]{a, b, c};
String finalString = "";
for (int i = 0; i < arr[0].length(); i++) {
int temp = Integer.parseInt("" + arr[0].charAt(i));
for (int j = 1; j < arr.length; j++) {
temp = temp & Integer.parseInt("" + arr[j].charAt(i));
}
finalString += temp;
}
System.out.println(finalString);
}
O/P
00100001

how to delete duplicate character from a string

The problem asks me to write a method to delete the duplicate characters from the original string and return the new string.For example, the original string is abracadabra and the result should be abrcd.
I was thinking about using StringBuilder to delete the character, but something went wrong when I tried to run the code. can anyone help me fix it.
public static String eliminateDuplicates(String str){
String result = "";
StringBuilder strings = new StringBuilder(str);
for(int i = 0; i<str.length(); i++){
for(int j = 1; j<str.length();j++){
if(str.charAt(i)==str.charAt(j)){
strings.deleteCharAt(j);
}
}
}
result = strings.toString();
return result;
}
Try this.
public static String eliminateDuplicates(String str){
int[] uniq = str.codePoints().distinct().toArray();
return new String(uniq, 0, uniq.length);
}
Using #P.J's idea
public static String eliminateDuplicates(String str) {
HashSet<Character> hashSet = new HashSet();
//A hashSet is a collection that only adds unique elements.
char[] toCharArray = str.toCharArray();
for (char c : toCharArray) {
hashSet.add(c);
}
StringBuilder answer = new StringBuilder();
for (Character character : hashSet) {
answer.append(character);
}
return answer.toString();
}
Try this code, maybe your can optimize :
public static String eliminateDuplicates(String source) {
StringBuilder result = new StringBuilder();
for (int i = 0, sLength = source.length(); i < sLength; i++) {
char readyToAdd = source.charAt(i);
boolean add = true;
for (int j = 0; j < result.length(); j++) {
if (readyToAdd == result.charAt(j)) {
add = false;
break;
}
}
if (add) result.append(readyToAdd);
}
return result.toString();
}
The code in question is iterating over input string but using the index to delete characters from the string builder object.
Every time the string builder deletes the character it will reduce in size. So, your code will fail with IndexOutofBoundsException. Please add the entire stack trace of the exception in the question to confirm, if that's the case.
A better approach to deleting duplicates is to create another string by iterating over the input string and then copying only the unique characters to new string. The new string can then be returned as a result.
This will also have better time complexity of O(n*m)compared to current code which had time complexity of O(n*n)
Try this
public static String eliminateDuplicates(String str){
StringBuilder result = new StringBuilder();
BitSet bs=new BitSet(256);
char[] chars=str.toCharArray();
char getChar=0;
for(int i=0;i<chars.length;i++){
getChar=chars[i];
if(!bs.get(getChar)){
result.append(getChar);
bs.set(getChar);
}
}
return result.toString();
}

Using StringBuilder to build a string out of extracted chars

I'm having trouble understanding why the string I'm trying to build out of this for-loop is only returning one character. I have a 4 character string that I iterate through for all the chars that match '0', but the logic only occurs once throughout. What am I missing?
private void updateDurationColor(SpinClassMovement movement){
String duration = (String) TextFormatUtil.getFormattedTimeInMinutesAndSeconds(movement.getMovementLengthInMinutes() + movement.getMovementLengthInSeconds());
for(int i = 0; i < duration.length(); i++){
if (duration.charAt(i) == '0'){
Character zero = duration.charAt(i);
StringBuilder colorDuration = new StringBuilder(zero);
colorDuration.append(zero);
setColor(mTimeRemaining,duration,colorDuration,Color.GRAY);
}
}
}
I think it's because your are initializing "colorDuration" inside the loop. Try this.
private void updateDurationColor(SpinClassMovement movement){
String duration = (String) TextFormatUtil.getFormattedTimeInMinutesAndSeconds(movement.getMovementLengthInMinutes() + movement.getMovementLengthInSeconds());
StringBuilder colorDuration = new StringBuilder();
for(int i = 0; i < duration.length(); i++){
if (duration.charAt(i) == '0'){
Character zero = duration.charAt(i);
colorDuration.append(zero);
setColor(mTimeRemaining,duration,colorDuration,Color.GRAY);
}
}
}

Removing characters from string efficiently

This may sound like a very simple question but how do you remove multiple different characters from a string without having to write a line for each, which is what I have laboriously done. I have written a string example below:
String word = "Hello, t-his is; an- (example) line."
word = word.replace(",", "");
word = word.replace(".", "");
word = word.replace(";", "");
word = word.replace("-", "");
word = word.replace("(", "");
word = word.replace(")", "");
System.out.println(word);
Which would produce "Hello this is an example line". A more efficient way is?
Use
word = word.replaceAll("[,.;\\-()]", "");
Note that special character - (hyphen) should be escaped by double backslashes, because otherwise it is considered to construct a range.
Although no more efficient than the original replace technique you could use
word = word.replaceAll("\\p{Punct}+", "");
to use a simple expression using replaceAll with a wider range of characters replaced
Without (ab)using regex, I would do that way:
String word = "Hello, t-his is; an- (example) line.";
String undesirable = ",.;-()";
int len1 = undesirable.length();
int len2 = word.length();
StringBuilder sb = new StringBuilder(len2);
outer: for (int j = 0; j < len2; j++) {
char c = word.charAt(j);
for (int i = 0; i < len; i++) {
if (c == undesirable.charAt(i)) continue outer;
}
sb.append(c);
}
System.out.println(sb.toString());
The advantage is performance. You don't need the overhead of creating and parsing a regular expression.
You could encapsulate that in a method:
public static String removeCharacters(String word, String undesirable) {
int len1 = undesirable.length();
int len2 = word.length();
StringBuilder sb = new StringBuilder(len2);
outer: for (int j = 0; j < len2; j++) {
char c = word.charAt(j);
for (int i = 0; i < len1; i++) {
if (c == undesirable.charAt(i)) continue outer;
}
sb.append(c);
}
return sb.toString();
}
public static String removeSpecialCharacters(String word) {
return removeCharacters(word, ",.;-()");
}
And then, you would use it this way:
public static void testMethod() {
String word = "Hello, t-his is; an- (example) line.";
System.out.println(removeSpecialCharacters(word));
}
Here is a performance test:
public class WordTest {
public static void main(String[] args) {
int iterations = 10000000;
long t1 = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
testAsArray();
}
long t2 = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
testRegex();
}
long t3 = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
testAsString();
}
long t4 = System.currentTimeMillis();
System.out.println("Without regex, but using copied arrays: " + (t2 - t1));
System.out.println("With precompiled regex: " + (t3 - t2));
System.out.println("Without regex, but using string: " + (t4 - t3));
}
public static void testAsArray() {
String word = "Hello, t-his is; an- (example) line.";
char[] undesirable = ",.;-()".toCharArray();
StringBuilder sb = new StringBuilder(word.length());
outer: for (char c : word.toCharArray()) {
for (char h : undesirable) {
if (c == h) continue outer;
}
sb.append(c);
}
sb.toString();
}
public static void testAsString() {
String word = "Hello, t-his is; an- (example) line.";
String undesirable = ",.;-()";
int len1 = undesirable.length();
int len2 = word.length();
StringBuilder sb = new StringBuilder(len2);
outer: for (int j = 0; j < len2; j++) {
char c = word.charAt(j);
for (int i = 0; i < len1; i++) {
if (c == undesirable.charAt(i)) continue outer;
}
sb.append(c);
}
sb.toString();
}
private static final Pattern regex = Pattern.compile("[,\\.;\\-\\(\\)]");
public static void testRegex() {
String word = "Hello, t-his is; an- (example) line.";
String result = regex.matcher(word).replaceAll("");
}
}
The output on my machine:
Without regex, but using copied arrays: 5880
With precompiled regex: 11011
Without regex, but using string: 3844
Here is a solution to do this with minimal effort; the toRemove string contains all character you don't want to see in the output:
public static String removeChars(final String input, final String toRemove)
{
final StringBuilder sb = new StringBuilder(input.length());
final CharBuffer buf = CharBuffer.wrap(input);
char c;
while (buf.hasRemaining()) {
c = buf.get();
if (toRemove.indexOf(c) == -1)
sb.append(c);
}
return sb.toString();
}
If you use Java 8 you can even use this (unfortunately there's no CharStream so the casts are necessary...):
public static String removeChars(final String input, final String toRemove)
{
final StringBuilder sb = new StringBuilder(input.length());
input.chars().filter(c -> toRemove.indexOf((char) c) == -1)
.forEach(i -> sb.append((char) i));
return sb.toString();
}
You could try using a regular expression with Java's String.replaceAll method:
word = word.replaceAll(",|\.|;|-|\(|\)", "");
If you're not familiar with regular expressions, | means "or". So we are essentially saying , or . or ; or - or ( or ).
See more: Java documentation for String.replaceAll
Edit:
As mentioned, my previous version will not compile. Just for the sake of correctness (even though it has been pointed out that this is not the optimal solution), here is the corrected version of my regex:
word = word.replaceAll(",|\\.|;|-|\\(|\\)", "");

Categories