Android - Clean char array quickly and effectively - java

Is it possible to clean a char array in Java (Android) quickly and effectively? Make an other loop on the treatment seem to be to much heavy to be an optimised solution, doesn't it ?
It's strange but it is impossible to find such a solution in Java on the internet without having to subscribe to a pay site ..
Thank's to your attention

You can use:
Arrays.fill(yourArray, ' ');// or any other char instead of ' '
Arrays class belongs to the java.util package. It uses generics so you can fill any kind of array.

Why do you need to clear a char array in the first place?
Most functions that want a char array to put some data in it (IO read, etc..) return the length of data that was put in, so you can disregard the rest of the data in char array.

Use a boolean to indicate that your array is invalid.

I would like to know whether predetermine the size of an array which will be completed by various data sizes, or let it size evolve according to the reception is the best way? This is intended to have the fastest processing.
Thank's

I think the correct answer to this question is to set each character of the char[] to null character by doing:
Arrays.fill(buffer, (char)0);
Or
Arrays.fill(buffer, '\0');
Doing Arrays.fill(buffer, '0'); will fill all the char[] with the character '0' instead of the null character.

Related

Fetching the last occurence in byte array without looping

I've been trying to fetch the last occurrence of '\n' from a byte array of fixed size(that can be defined by me), i.e '\' & 'n' occur together.
What I tried doing is
Looping the byte array from (0 to size) and (size to 0), but I need to avoid for loops since I will be processing a lot of arrays.
Convert the byte to char and processing on that
Is there a more better solution than this? I'm a beginner to data structures and doing this in Java.
Thanks in advance.
One can't find something unless one looks. You have to examine the array to find specific bytes within it. There is no getting around that. Remember that you can break out of the loop if you start from the tail, because the first "\\n" you find will be the last occurrence in the array.
Since you've edited your question, let me add this. You can loop two-by-two, and if the byte in question is either '\\' or 'n', then you can check the next byte or the previous byte for the other character. That might be more efficient.

What is the purpose of the char datatype?

I am currently reading a textbook on Java and each chapter involving the String datatype also discusses char. My question is, what purpose does char have in the real world?
The only thing I have found is that because String is immutable, it makes it a poor choice for passwords. Thus, one should choose a character array (char[]) over String. However, Java does have a mutable class for strings called StringBuilder; would that not be just as suitable a replacement for strings as is char[]?
This has already been answered in the comments really :)
A String is a collection of Chars. Without Chars you would have nothing to build Strings from.
Because Char[] and dealing with Char[] is so important they warrant having their own class to handle the processing of them - hence String.
In your coding you are unlikely to use the Char datatype directly unless you are processing Strings or handling passwords. The only reason Char[] is used for passwords is because it's harder to accidentally print them into logs/view them in memory/put them into string caches, etc and because once you have finished with it you can explicitly zero the elements in the Array so it never stays in memory longer than needed.

Char vs String in Java? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am learning Java this year as part of the AP Computer Science curriculum, and while I was reading about "Char" and "String" I could not understand why one would bother to use "Char" and only be able to store one character rather than just use "String" and be able to store much more than that. In short what's the point of "char" if it can only store a single character?
People are mentioning memory concerns, which are valid, but I don't think that's a very important reason 99% of the time. An important reason is that the Java compiler will tell you if you make a mistake so you don't have to figure it out on your own.
For example, if you only want 1 character for a variable, you can use a char to store the value and now nobody can put anything else in there without it being an error. If you used a String instead, there could be two characters in the String even though you intended that to never be possible. In fact, there could be 0 characters in the String which would be just as bad. Also, all your code that uses the String will have to say "get the first character of the String" where it could simply say, "give me the character".
An analogy (which may not make sense to you yet, unfortunately) would be, "Why would I say a Person has a Name when I could say a Person has a List of Names?" The same reasons apply. If you only want a Person to have one Name, then giving him a list of Names adds a lot maintenance overhead.
You could consider this analogy:
You need one apple. Would you prefer to have one apple in your hand, or a big box that could contain more apples, but only needs to contain the one?
The char primitive datatype is easier to work with than the String class in situations where you only need one character. It's also a lot less overhead, because the String class has a lot of extra methods and information that it needs to store to be efficient at handling string with multiple characters. Using the String class when you only need one character is basically overkill. If you want to read from a variable of both types to get the character, this is the code that would do that:
// initialization of the variables
char character = 'a';
String string = "a";
// writing a method that returns the character
char getChar()
{
return character; // simple!
}
char getCharFromString()
{
return string.charAt(0); // complicated, could fail if there is no character
}
If this code looks complicated, you can ignore it. The conclusion is that using String when you only need one character is overcomplicating things.
Basically, the String class is used when you need more than one character. You could also just create an array of chars, but then you would not have the useful methods of the String class, such as the .equals() and .length() methods.
Strings are objects. Objects always go on the dynamic storage. Storing one-character string would require at least a dozen of bytes.
chars (not Chars) are primitives. They take fixed amount of space (2 bytes). In situations when you need to process a single character, creating one-character string is a waste of resources. Moreover, when you expect to see a single character, using strings would require validation that the data passed in has exactly one character. This would be unacceptable in situations when you must be extremely fast, such as character-based input and output.
To summarize, you need a char because of
Memory footprint - a char is smaller than a String of one character
Speed of processing - creating objects carries an overhead
Program's maintainability - Knowing the type makes it easier for you and for the readers of your code to know what kind of data is expected to be stored in a char variable.
char take up less memory for times when you really only need one character. There are also multiple other applications for using a single character.
char is a primitive datatype while string is an object which comes at greater overhead.
A string is also made up of char, so there's that too.
Because the char takes up less memory!
Also the char is stored in memory and NOT as a reference value so theoretically its faster to access the char (You'll understand that more later)
***Note: I once had this same thought when I first started programming about why use an int when you can use a long and not have to worry about large numbers. This tells me you're on your way to be a great programmer! :)
char is a primitive type while String is a true Object. In some cases where performance is a concern it's conceivable that you would only want to use primitives.
Another case in which you would want to use char is when you're writing Java 1.0 and you're tasked with creating the String class!
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
Everything in java can be reduced to primitive types. You can write any program with primitive types. So you need some kind of minimalist way of storing text. A char is also really just a byte, that is interpreted as a character.
Also if you want to loop though all characters in a string you would do:
char[] chArr = str.toCharArray();
for(int i = 0 ; i < chArr.length ; i++)
{
//do something with chArr[i];
}
This would be much more awkward trying to substring out an exact character from the String.
Lot of answers here already. While the memory concerns are valid, you have to realize there are times when you want to directly manipulate characters. The word ladder game
where you try to turn one word into another by changing one character at a time is an example I had to do in a programming class. Having a char type lets you manipulate a singe character at a time. It also lets you assign an int to a char that maps to your local character set.
You can do thing like char c = 97; and that will print out as a. You can do things like increment a character from 97 to 122 to print out all lowercase characters. Sometimes this actually is useful.

Normalizing/unaccenting text in Java

How can I normalize/unaccent text in Java? I am currently using java.text.Normalizer:
Normalizer.normalize(str, Normalizer.Form.NFD)
.replaceAll("\\p{InCombiningDiacriticalMarks}+", "")
But it is far from perfect. For example, it leaves Norwegian characters æ and ø untouched. Does anyone know of an alternative? I am looking for something that would convert characters in all sorts of languages to just the a-z range. I realize there are different ways to do this (e.g. should æ be encoded as 'a', 'e' or even 'ae'?) and I'm open for any solution. I prefer to not write something myself since I think it's unlikely that I will be able to do this well for all languages. Performance is NOT critical.
The use case: I want to convert a user entered name to a plain a-z ranged name. The converted name will be displayed to the user, so I want it to match as close as possible what the user wrote in his original language.
EDIT:
Alright people, thanks for negging the post and not addressing my question, yay! :) Maybe I should have left out the use case. But please allow me to clarify. I need to convert the name in order to store it internally. I have no control over the choice of letters allowed here. The name will be visible to the user in, for example, the URL. The same way that your user name on this forum is normalized and shown to you in the URL if you click on your name. This forum converts a name like "Bășan" to "baan" and a name like "Øyvind" to "yvind". I believe it can be done better. I am looking for ideas and preferably a library function to do this for me. I know I can not get it right, I know that "o" and "ø" are different, etc, but if my name is "Øyvind" and I register on an online forum, I would likely prefer that my user name is "oyvind" and not "yvind". Hope that this makes any sense! Thanks!
(And NO, we will not allow the user to pick his own user name. I am really just looking for an alternative to java.text.Normalizer. Thanks!)
Assuming you have considering ALL of the implications of what you're doing, ALL the ways it can go wrong, what you'll do when you get Chinese pictograms and other things that have no equivalent in the Latin Alphabet...
There's not a library that I know of that does what you want. If you have a list of equivalencies (as you say, the 'æ' to 'ae' or whatever), you could store them in a file (or, if you're doing this a lot, in a sorted array in memory, for performance reason) and then do a lookup and replace by character. If you have the space in memory to store the (# of unicode characters) as a char array, being able to run through the unicode values of each character and do a straight lookup would be the most efficient.
i.e., /u1234 => lookupArray[1234] => 'q'
or whatever.
so you'll have a loop that looks like:
StringBuffer buf = new StringBuffer();
for (int i = 0; i < string.length(); i++) {
buf.append(lookupArray[Character.unicodeValue(string.charAt(i))]);
}
I wrote that from scratch, so there are probably some bad method calls or something.
You'll have to do something to handle decomposed characters, probably with a lookahead buffer.
Good luck - I'm sure this is fraught with pitfalls.

Help converting input string into Unicode integers in Java

I've been set an assignment which requires me to capture the input of 5 strings, convert them to uppercase, output them as a string, convert them to their Unicode integers (using the getNumericValue method) and then manipulate the integers using some basic operators.
I get the first part but I am having trouble with the following:
Using the getNumericValue to convert
my single character literal strings
into their Unicode integer
counterparts.
Being able to assign these ints to
variables so I can further process s
them with operators, all the
examples I have seen have been
simple printing out the number and
not assigning it to a variable,
since I am a Java noob the syntax is
still a little confusing for me.
My code is here
If there is a cleaner way of doing what I want please suggest so but without the use of arrays or loops.
I don't understand why you don't want to do this without arrays or loops.
You can get the unicode values (as ints) making up the string via String.codePointAt(), or get the characters via charAt() followed by a getNumericValue() for each character. But regardless, you're going to have to iterate over the set of characters in the string via a loop, or perhaps recursion.
Yes, sounds like op needs to continue researching avenues of learning.
// difficult to code without interfering with
// instructor's prerogative
char ( array ) = String.getchars();
// Now what, unroll the loop?
...
As noted by Brian, loops are fundamental. I cannot imagine getChars being assigned before simple array techniques.

Categories