converting char array of particular length into a string - java

i need to convert char array into string , the problem in doing this is......i need to convert the character in char array of particular length say k to string. ie, char array is "b" .b takes value dynamically.....for instance take as "p,a,p,e,r,s" now k value also dynamic ,for this word "k=5" ,and then only 4 characters in char array "b" should be converted into string...ie the string should print as "paper"........
the code what i have now is
for(int c=0;c<=k;c++)
{
System.out.print(b[c]);
}
str=new String(b);
System.out.println(str);
where b[c] prints correct value(in char array) as "paper". While converting to string str (in program) it prints as "papers" itself....can anyone give me solution for this?

You can use a different constructor of String that lets you specify the array along with the start point and number of characters to use.
In your case, you would try:
str = new String( b, 0, k );

char newArr[] = new char[k];
for (int i = 0; i < k; i++) {
newArr[i] = b[i];
System.out.print(b[i]); // print until the kth index
}
return new String(newArr);

Related

Why can't I see the contents in Java char array neither in eclipse console nor in the debugger?

I not able to print char array to eclipse console or see the array contents while debugging in eclipse. I have written a program to return 1st non-repeating character index from a string using arrays. The program works & is very straightforward, but I find it very amusing that I cannot see the contents of the char array while I manipulate/debug the program. The SOP statement prints null OR \u0000. How can I see the actual contents of array 'a' in the below program ?
public static int getFirstNPCv2 (String s) {
char a[] = new char[26];
s=s.toLowerCase();
for (char c : s.toCharArray()){
a[c - 'a']++;
//System.out.println(a[c - 'a']);
}
System.out.println(a);
for (char c : s.toCharArray()){
if(a[c - 'a'] == 1){
return s.indexOf(c);
}
}
return -1;
}
getFirstNPCv2("titanic") returns 3 which is correct, but why can't I see the contents of array 'a'
This is because you don't hold any meaningful characters in your char array.
You are actually holding numbers in your char array. You created new char array and initial value of its elements is 0.
char a[] = new char[26];
Later on you will increment some elements of this array if they match index of character that is contained in your input string:
for (char c : s.toCharArray()){
a[c - 'a']++;
//System.out.println(a[c - 'a']);
}
Still, your char array doesn't hold any meaningful characters. It will have elements with values of 0,1,2,3... depending on your input string, and those values don't represent any readable letter or number. Still this doesn't prevent you from printing values stored in char array a. You can print them this way:
for(int i = 0; i<a.length; i++)
{
int b = a[i];
System.out.print(b);
}
I think for your approach you should have used array of int. Happy coding.
This is because you declared a as an array of characters and assign numeric values to each element.
In your case, all characters within the array have a value 0, 1 or 2.
These are non-printable characters.
Declare it as int a[] = new int[26];
Furthermore, instead of System.out.println(a), you should use System.out.println(Arrays.toString(a)).

Casting a specific element of an array - java

I have an array as:
String letters [] = {a, b, c, d, e};
Can I cast a specific element let's say "a" ? I want to get its ascii value, so I did this but it is not working:
for (int i = 0; i < letters.length; i++) {
Integer iDecimal = (int) a[0]; // the a[0] is wrong!!
System.out.print(iDecimal);
}
Any ideas about how to cast in such cases?
You are trying to cast a[0] which doesn't exist, to access your array you need to do letters[0] and then try working with it. I suggest changing type of your array to char and then casting it, you can't do that with String.
Declare the array as object array, but be aware that this is bad coding style, since you are mixing different types in one array.
Object letters [] = {5, "b", 'c'};
The object array contains an integer, a string, and a character you may then iterate over the array and test what object type you have.
The integer element is autoboxed to an Integer-Object.
But again i would not recommend doing so, since element testing is expensive.
for (int i = 0; i < letters.length; i++) {
if (a[i]) instanceof Integer)
Integer iDecimal = (Integer) a[i];
}
Assuming you want just the ASCII code for the first character in each string in your array, then you can can access that char then cast it to an int.
for (int i = 0; i < letters.length; i++) {
int iChar = (int) letters[i][0];
System.out.print(iChar);
}
letters[i] is the ith string in the letters array.
letters[i][0] is the first character of the ith string in the letters array, and will be of type char.
(int)letters[i][0] is the integer value equivalent to the first character of the ith string in the letters array.
Strictly this will give the first UTF-16 word in the string, but for values <127 it will be the same as the ASCII value.
ints are not decimal values, so don't call them decimals. The BigDecimal type is used for decimal values.

Replace entire char array with different char

I'm very new to programming and I've spent some time looking for a way to do this that I can understand. I'm making a hangman game in java, it's all text based, and I've got almost the entire thing done. All I need is to replace a character array that holds the value of a random word to be replaced with dashes. So if the word was "java" I need to change that character array to "----". Since the word is chosen at random from a list, I have to find a way to use the length of the word to apply those dashes, but I'm not sure how.
Any help is appreciated!
A simple way to replace all the characters by '_' would be :
char[] charArray = {'W','O','R','D'};
Arrays.fill(charArray, '_');
I will give you an example based on what you have provided so far with java and ----:
public class Program {
public static void main(String[] args) {
String value = "java";
char[] array = value.toCharArray();
// Convert string to a char array.
for(int i = 0; i < value.length(); i++)
{
array[i] = '-';
}
// Loop over chars in the array.
for (char c : array) {
System.out.print(c);
}
}
}
OK, a few things that may be helpful in solving this task:
If you have a String you can easily get the length of that String like this:
String word = "java";
int lengthOfWord = word.length();
You can easily edit the contents of an array by accessing the individual elements:
char[] array = new char[4];
array[0] = '-';
array[1] = '_';
array[2] = '-';
array[3] = '_';
If you want to do something repeatedly and know how often you want to do that, using a for-loop is often a great idea. And you can use the counter within the loop. So for example:
int sum = 0;
for(int i = 0; i < 10; i++) {
sum += i;
}
So, combine those pieces of information and you can replace every element of that array. :-)

how to convert a String of int into a table int[]

I made a function that requires an int[], Conflict(int[] tab), and as you all know we extract information from a JTextField in the form of an String (s) ,so I then convert in into an integer with:
int input=Integer.parseInt(s);
Now, I found this way to do it :
int input= 1234;
String input= String.valueOf(input);
Vector<int> tab = new Vector<int>();
for (int cpt = 0; cpt <input.length(); cpt++)
{
tab.add(Integer.valueOf(input.substring(cpt, cpt+1)).intValue());
}
but I'm looking for a simple way without the vector ,so again the Question is How can I convert the input (int) into a table of int[] so that I can use it in the Conflict function?
Here is an answer to my question for all of you who's looking to turn an int into an int[] using a string with a very smart simple trick
tcst = ""+inputc;
int tcn = tcst.length();
int[] tctab = new int[tcn];
for(int h=0; h<tcn; h++){
tctab[h] = (int) Integer.parseInt("" + tcst.charAt(h));
}
If you have a String of number like "12345" best way is to convert it into char array using toCharArray() method of string. Once you get a char array of numbers these char can be used as integer in you program. just when you get an element from the char array and convert it into int by using getNumericValue() method of character
If your input is a String (from a JTextField), then I don't see why you're converting it to an integer, just to convert it to a String again.
To go from String to int[], here's a way to do it.
char[] chars = inputString.toCharArray();
int[] result = new int[chars.length];
for(int i=0; i<chars.length; i++){
result[i] = Character.getNumericValue(chars[i]);
}

How to create char[][] from String?

I got a little problem here with Java and I am fairly new to it.
My program reads a String via InputStreamReader and saves it in the String input.
How do I save the elements of the String in a 2d char array with n x m elements?
Edit:
I think I´ve got a solution:
I used 2 for-loops (is that the right english translation for it? ) and .toCharArray to convert the String.
public static char[][] transform (String text, int arrBreite, int arrLaenge) {
char[][] returnArray = new char[arrBreite][arrLaenge];
char[] buffer = text.toCharArray();
for (int i = 0; i < arrBreite; i++) {
for (int j = 0; j <arrLaenge; j++) {
if (((i * arrBreite) + j) > buffer.length - 1) returnArray[i][j] = " ".charAt(0);
else returnArray[i][j] = buffer[(i*arrBreite)+j];
}
}
return returnArray;
}
Thanks for your help guys.
You can use the toCharArray() method to get a char array from your String.
If you need to split with a given delimiter to determine the array lines, you use first the Split method on the String, then use toCharArray to create your 2 dimensional array.
You should use String.toCharArray().

Categories

Resources