char array with variable length - java

How should i declare a char array whose size ranges from 1 to 100 and I cannot make an array of size 100 because i have to make many arrays.
My input is:
"bjomboleji";
"bnmjsjbfhaihfaihfga";
"zbihgfbjbnsdfbnbfkj";
"bnxbz";
and i have to check the common occurence of characters.

Use ArrayList for dynamic array.
List<Chracter> array = new ArrayList<Chracter>();

Use a String to assign the value, then use toCharArray to convert to an array (if you really need a character array)

Use a StringBuilder. It is a "mutable sequence of characters."
This is a better solution than a List<Character> as it avoids the need to create Character objects from char primitives.
This is a better choice than manipulating a String as String objects are immutable and manipulation results in additional objects being created.

Variable length char is basically interface CharSequence which is implemented by String, StringBuilder, StringBuffer. So you can use any of it for variable char array.

To my understanding you need to count occurrences of a character in a string.If that's the case here is an example. there is no need to convert it to char array
public class Test {
public static void main(String[] args) {
String x="dhakjkfhajfhuagjkadmnfd";
String y="tskashguadmnsdm,as";
String Check_Character="s";
//Availability
System.out.println("X has Check_Character :"+x.contains(Check_Character)); //false
System.out.println("Y has Check_Character :"+y.contains(Check_Character));//true
//Number of occurrences
System.out.println("X has Check_Character :"+((x+" ").split(Check_Character).length-1)+" : times");//0 times
System.out.println("Y has Check_Character :"+((y+" ").split(Check_Character).length-1)+" : times");//4times
}
}
Otherwise you can use a list instead of an array or use this.
String z="dhakjkfhajfhuagjkadmnfd";
char c[]=z.toCharArray();

Related

Java - How to display all substrings in String without using an array

I have a string which is :
1|name|lastname|email|tel \n
2|name|lastname|email|tel \n
I know that I have to use a loop to display all lines but the problem is that in my assignment
I can't use arrays or other classes than String and System.
Also I would like to sort names by ascending order without using sort method or arrays.
Do I have to use compareTo method to compare two names ?
If that's the case, how do I use compareTo method to sort names.
For example, if compareTo returns 1, that means that the name is greater than the other one. In that case how do I manage the return to sort name properly in the string ?
To display all substrings of the string as in the example, you can just go through all characters one by one and store them in a string. Whenever you hit a delimiter (e.g. | or \n), print the last string.
Here's a thread on iterating through characters of a string in Java:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
If you also need to sort the names in ascending order without an array, you will need to scan the input many times - sorting N strings takes at least N*log(N) steps. If this is a data structure question, PriorityQueue should do the trick for you - insert all substrings and then pop them out in a sorted fashion :)
building on the previous answer by StoneyKeys, since i do not have the privilege to comment, you can use a simple if statement that when the char is a delimiter, System.out.println() your previous scanned string. Then you can reset the string to an empty string in preparation for scanning the next string.
In java, there are special .equals() operators for strings and chars so when you won't be using == to check strings or char. Do look into that. To reset the value of string just assign it a new value. This is because the original variable points at a certain string ie "YHStan", by making it point at "", we are effectively "resetting" the string. ie scannedstr = "";
Please read the code and understand what each line of code does. The sample code and comments is only for your understanding, not a complete solution.
String str ="";
String value = "YH\nStan";
for (int i=0; i <value.length(); i++) {
char c = value.charAt(i);
String strc = Character.toString(c);
//check if its a delimiter, using a string or char .equals(), if it is print it out and reset the string
if (strc.equals("\n")) {
System.out.println(str);
str ="";
continue; // go to next iteration (you can instead use a else if to replace this)
}
//if its not delimiter append to str
str = str +strc;
//this is to show you how the str is changing as we go through the loop.
System.out.println(str);
}
System.out.println(str); //print out final string result
This gives a result of:
Y
YH
YH
S
St
Sta
Stan
Stan

Printing 1D array of chars, ints in java using System.out.println(arr)

I am printing a 1d array of chars by using System.out.println(arr) and I get the characters in the array (not space seperated). When I do the same by adding a "/t", the output changes and it now prints the address of the char array.
I tried to print a 1d array of ints using System.out.println(arr), but the results were different and it printed the location of the array in memory.
Please tell what is going on and how is it all implemented.
import java.io.*;
import java.math.*;
import java.util.*;
import java.lang.*;
class Main3{
public static void main(String[] args)throws java.lang.Exception{
int[] intArr = {1,2,3,4};
char[] charArr = {'a' , 'b' };
System. out.println(intArr); // prints the address of the intArr
System. out.println(charArr); // prints the charArr contents
System.out.println("\t" + charArr); // prints the address of the charArr after a tab
}
}
PrintStream has a method that accepts a char[].
However when you do "\t" + charArray java tries to do String concatenation. To do this it first has to convert charArray to a String using the Object#toString method(JLS 5.1.11). Then it passes the String into println.
The following print statement:
System.out.println(charArr);
invokes the PrintStream#println(char[]) method. From the documentation:
The characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
Whereas the next print statement:
System.out.println("\t" + charArr);
converts the charArray to String, by invoking the toString() method of Object class, as arrays don't override it. And then the method PrintStream#println(String) is invoked.
So, the above print statement is equivalent to:
System.out.println("\t" + charArr.toString());
Look into the Object#toString() method to see how it forms the string for the array.
The way to access the elements of the array is with bracket notation. So for example if you want the get the int at index 0 of the intArr you could write
System.out.println(intArr[0]);
where the number in brackets is the index of the element you want or you could iterate over all of them with
for(int i = 0; i < intArr.length; i++){
System.out.println(intArr[i]);
}
This will work as long as whats in the array is not an object - in which case it will print the address.

Java: Create an array with letter characters as index

Is it possible to create in Java an array indexed by letter characters ('a' to 'z') rather than by integers?
With such an array "a", I would like to useit in this way, for example
print (a['a']);
Is it possible to create in Java an array indexed by letter characters
('a' to 'z') rather than by integers?
Of course it is possible.
You could do this either like this:
char theChar = 'x';
print (a[theChar - 'a']);
or assuming handling only ASCII strings just declare the array of size 256. The directly index the array using your character.
char[] a = new char[256];
char theChar = 'x';
print (a[theChar]);
Now you don't care if it is uppercase/lower case or whatever.
Actually if you are interested specifically for ASCII strings using a Map could be overkill compared to a simple array. The array doesn't waste so much space and perhaps a Map (a very efficient construct) is too much for such a simple task.
Use a Map instead.
Map<Character, Object> myMap = new HashMap<Character, Object>();
myMap.put('a', something);
print(myMap.get('a'));
On the other hand, as others already suggested, you can use a char as index (but you would leave all array elements 0...'a'-1 empty):
String[] a = new String['z' + 1];
a['a'] = "Hello World";
System.out.println(a['a']);
You could create an array of 26 elements and always substract 'a' from you char index:
int[] array = new int[26];
array['a'-'a']=0;
array['b'-'a']=1;
\\ etc...
What about something simple like this?
public static int getLetterValue(char letter) {
return (int) Character.toUpperCase(letter) - 64;
}
and use it like so:
System.out.println(a[getLetterValue('a'));
This will fail pretty hard as it stand at the moment. You will need to check it's within range etc.
Alternatively you could implement the Java List interface and override the .get and .add methods so that they can use chars. But that brings me to my next point.
It's better to use a data structure that handles exceptions better, and is designed for that sort of use case. A Map is a much better choice.
Yes and no. Yes because you can do it and it will compile. Try the following code:
class foo {
public static void main(String[] args) throws Exception {
int a[] = new int[100];
a['a'] = '1';
System.out.printf("%d\n", a['a']);
}
}
No, because the chars will be implicitly converted to ints, which doesn't sound like what you're looking for.
The data structure you are looking for is called Map in Java land.
This data structure is known by various names, such as associative array in PHP; dictionary in C#, Python; hash in Ruby etc which leads to this kind of confusion.
You could do something like this:- for eg:
char[] a = new char[]{'s','t'};
int[] result = new int[256];
result[a[0]]= 100;
System.out.println(result['s']);//will print 100
No, You cannot do that. In the situation you should use Map instead.
I think this is a duplicate question! See Can Java use String as an index array key? (ex: array["a"]=1;) .
You should use a map to map the letter to the value and call get to get the value.

what is 'new StringBuffer(aString)' in java?

I see a program to reverse a string
public class ReverseName{
public static void main(String[]args)
{
String name=args[0];
String reverse=new StringBuffer(name).reverse().toString();
System.out.println(reverse);
}
}
so what is new StringBuffer(name).reverse().toString(); all about?
String reverse=new StringBuffer(name).reverse().toString();
Let's break this down.
new StringBuffer(name)
First off we create a new StringBuffer (I'd have used StringBuilder as we don't need thread safety) with the contents of name. This just allows a more peformant way to append strings but here it's used for the next part.
.reverse()
This calls the reverse method on the StringBuffer which returns a reversed StringBuffer.
.toString();
Finally this is turned back into a String.
You can split that into 3 lines for understanding
StringBuffer reverseBuffer = new StringBuffer(name); // Creating new StringBuffer object
reverseBuffer = reverseBuffer.reverse(); //Reversing the content using StringBuffer
String reverse = reverseBuffer.toString(); // Converting StringBuffer to String and saving in reverse
just a StringBuffer object reversing a string
You instantiate the StringBuffer object with the "name" String object , then reverse it.
From the JAVA API
public StringBuffer reverse()
Causes this character sequence to be replaced by the reverse of the sequence. If there are any surrogate pairs included in the sequence, these are treated as single characters for the reverse operation. Thus, the order of the high-low surrogates is never reversed. Let n be the character length of this character sequence (not the length in char values) just prior to execution of the reverse method. Then the character at index k in the new character sequence is equal to the character at index n-k-1 in the old character sequence.
Note that the reverse operation may result in producing surrogate pairs that were unpaired low-surrogates and high-surrogates before the operation. For example, reversing "\uDC00\uD800" produces "\uD800\uDC00" which is a valid surrogate pair.
Returns:
a reference to this object.
Since:
JDK1.0.2
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuffer.html#reverse%28%29
Actually String is an immutable class, that means once object of String is created its contents cannot be modified. Therefore we use StringBuffer to construct strings. In above example, object of StringBuffer is created with content name, String in name is reversed in same object of StringBuffer(as it is mutable). Again converted to String object and assigned that object to reverse object reference.

Splitting string N into N/X strings

I would like some guidance on how to split a string into N number of separate strings based on a arithmetical operation; for example string.length()/300.
I am aware of ways to do it with delimiters such as
testString.split(",");
but how does one uses greedy/reluctant/possessive quantifiers with the split method?
Update: As per request a similar example of what am looking to achieve;
String X = "32028783836295C75546F7272656E745C756E742E657865000032002E002E005C0"
Resulting in X/3 (more or less... done by hand)
X[0] = 32028783836295C75546F
X[1] = 6E745C756E742E6578650
x[2] = 65000032002E002E005C0
Dont worry about explaining how to put it into the array, I have no problem with that, only on how to split without using a delimiter, but an arithmetic operation
You could do that by splitting on (?<=\G.{5}) whereby the string aaaaabbbbbccccceeeeefff would be split into the following parts:
aaaaa
bbbbb
ccccc
eeeee
fff
The \G matches the (zero-width) position where the previous match occurred. Initially, \G starts at the beginning of the string. Note that by default the . meta char does not match line breaks, so if you want it to match every character, enable DOT-ALL: (?s)(?<=\G.{5}).
A demo:
class Main {
public static void main(String[] args) {
int N = 5;
String text = "aaaaabbbbbccccceeeeefff";
String[] tokens = text.split("(?<=\\G.{" + N + "})");
for(String t : tokens) {
System.out.println(t);
}
}
}
which can be tested online here: http://ideone.com/q6dVB
EDIT
Since you asked for documentation on regex, here are the specific tutorials for the topics the suggested regex contains:
\G, see: http://www.regular-expressions.info/continue.html
(?<=...), see: http://www.regular-expressions.info/lookaround.html
{...}, see: http://www.regular-expressions.info/repeat.html
If there's a fixed length that you want each String to be, you can use Guava's Splitter:
int length = string.length() / 300;
Iterable<String> splitStrings = Splitter.fixedLength(length).split(string);
Each String in splitStrings with the possible exception of the last will have a length of length. The last may have a length between 1 and length.
Note that unlike String.split, which first builds an ArrayList<String> and then uses toArray() on that to produce the final String[] result, Guava's Splitter is lazy and doesn't do anything with the input string when split is called. The actual splitting and returning of strings is done as you iterate through the resulting Iterable. This allows you to just iterate over the results without allocating a data structure and storing them all or to copy them into any kind of Collection you want without going through the intermediate ArrayList and String[]. Depending on what you want to do with the results, this can be considerably more efficient. It's also much more clear what you're doing than with a regex.
How about plain old String.substring? It's memory friendly (as it reuses the original char array).
well, I think this is probably as efficient a way to do this as any other.
int N=300;
int sublen = testString.length()/N;
String[] subs = new String[N];
for(int i=0; i<testString.length(); i+=sublen){
subs[i] = testString.substring(i,i+sublen);
}
You can do it faster if you need the items as a char[] array rather as individual Strings - depending on how you need to use the results - e.g. using testString.toCharArray()
Dunno, you'll probably need a method that takes string and int times and returns a list of strings. Pseudo code (haven't checked if it works or not):
public String[] splintInto(String splitString, int parts)
{
int dlength = splitString.length/parts
ArrayList<String> retVal = new ArrayList<String>()
for(i=0; i<splitString.length;i+=dlength)
{
retVal.add(splitString.substring(i,i+dlength)
}
return retVal.toArray()
}

Categories