Java character array initializer - java

I tried to make a program that separates characters.
The question is:
"Create a char array and use an array initializer to initialize the array with the characters in the string 'Hi there'. Display the contents of the array using a for-statement. Separate each character in the array with a space".
The program I made:
String ini = "Hi there";
char[] array = new char[ini.length()];
for(int count=0;count<array.length;count++) {
System.out.print(" "+array[count]);
}
What should I do to fix this problem?

Here's how you convert a String to a char array:
String str = "someString";
char[] charArray = str.toCharArray();
I'd recommend that you use an IDE when programming, to easily see which methods a class contains (in this case you'd be able to find toCharArray()) and compile errors like the one you have above. You should also familiarize yourself with the documentation, which in this case would be this String documentation.
Also, always post which compile errors you're getting. In this case it was easy to spot, but when it isn't you won't be able to get any answers if you don't include it in the post.

you are doing it wrong, you have first split the string using space as a delimiter using String.split() and populate the char array with charcters.
or even simpler just use String.charAt() in the loop to populate array like below:
String ini="Hi there";
char[] array=new char[ini.length()];
for(int count=0;count<array.length;count++){
array[count] = ini.charAt(count);
System.out.print(" "+array[count]);
}
or one liner would be
String ini="Hi there";
char[] array=ini.toCharArray();

char array[] = new String("Hi there").toCharArray();
for(char c : array)
System.out.print(c + " ");

Here is the code
String str = "Hi There";
char[] arr = str.toCharArray();
for(int i=0;i<arr.length;i++)
System.out.print(" "+arr[i]);

Instead of above way u can achieve the solution simply by following method..
public static void main(String args[]) {
String ini = "Hi there";
for (int i = 0; i < ini.length(); i++) {
System.out.print(" " + ini.charAt(i));
}
}

You initialized and declared your String to "Hi there", initialized your char[] array with the correct size, and you began a loop over the length of the array which prints an empty string combined with a given element being looked at in the array. At which point did you factor in the functionality to put in the characters from the String into the array?
When you attempt to print each element in the array, you print an empty String, since you're adding 'nothing' to an empty String, and since there was no functionality to add in the characters from the input String to the array. You have everything around it correctly implemented, though. This is the code that should go after you initialize the array, but before the for-loop that iterates over the array to print out the elements.
for (int count = 0; count < ini.length(); count++) {
array[count] = ini.charAt(count);
}
It would be more efficient to just combine the for-loops to print each character out right after you put it into the array.
for (int count = 0; count < ini.length(); count++) {
array[count] = ini.charAt(count);
System.out.println(array[count]);
}
At this point, you're probably wondering why even put it in a char[] when I can just print them using the reference to the String object ini itself.
String ini = "Hi there";
for (int count = 0; count < ini.length(); count++) {
System.out.println(ini.charAt(count));
}
Definitely read about Java Strings. They're fascinating and work pretty well, in my opinion. Here's a decent link: https://www.javatpoint.com/java-string
String ini = "Hi there"; // stored in String constant pool
is stored differently in memory than
String ini = new String("Hi there"); // stored in heap memory and String constant pool
, which is stored differently than
char[] inichar = new char[]{"H", "i", " ", "t", "h", "e", "r", "e"};
String ini = new String(inichar); // converts from char array to string
.

Another easy way is that you use string literal and convert it to charArray in declaration itself.
Something like this -
char array[] = "Hi there".toCharArray();
//Print with white spaces
for(char c : array)
System.out.print(c + " ");

Related

java string [] array remove special character

how to remove "," in below string specified at s[0,2] location(818001,818002)(151515,151515) and store again to string []
String[] s = {"818001,818002","121212","151515,151515"};
You should explain more detailed your problem.
I think what you want is this:
s = '(818001,818002)(151515,151515)' //the string you have.
s = s.replace(')(',',').replace('(','').replace(')','');// output "818001,818002,151515,151515"
final_string = s.split(','); //output (4) ["818001", "818002", "151515", "151515"]
If you need to remove a comma (or any other char for that matter) in your String array indices the simplest is to iterate through the array and use String.replace():
String[] s = {"818001,818002","121212","151515,151515"};
for(int i=0; i<s.length; i++) {
s[i] = s[i].replace(",", "");
}
System.out.print(Arrays.toString(s)); // [818001818002, 121212, 151515151515]

Sentence reverse in java

So i'm trying to reverse a sentence and even though I don't have any errors when compiling, it tells me my reverse sentence is out of bounds.
-It should work like this: "hello, world!" --> !dlrow ,olleh"
Said code:
String sentence="this is a sentence!";
String reverseSentence=sentence;
for(int counter=0;counter<sentence.length();counter++)
{
char charToReplace,replaceChar;
charToReplace = reverseSentence.charAt(counter);
replaceChar = sentence.charAt(sentence.length()-counter);
reverseSentence=reverseSentence.replace(charToReplace, replaceChar);
System.out.println(reverseSentence);
}
The reason for the exception you are getting is that in sentence.charAt(sentence.length()-counter), sentence.length()-counter is out of bounds when counter is 0. Should be sentence.length()-1-counter.
However, as Tunaki commented, there are other problems with your code. I suggest you use a StringBuilder to construct the reversed String, instead of using replace (which would replace any occurrence of the first character with the second character).
You can use character arrays to implement your requirement like this,
String sentence = "ABDEF";
char[] firstString = sentence.toCharArray();
char[] reversedString = new char[sentence.length()];
for (int counter = 0; counter < sentence.length(); counter++) {
reversedString[counter] = firstString[sentence.length() - counter -1];
}
System.out.println(String.copyValueOf(reversedString));
It doesn't show you an error because the Exception concerning the indexes happen at RunTime.
Here :
replaceChar = sentence.charAt(sentence.length()-counter);
You're trying to access index 19 of your String (19-0). Replace it with :
replaceChar = sentence.charAt(sentence.length()-counter-1);
I'd recommend to use a StringBuilder in your situation though.
Either use the reverse() method :
String sentence = "this is a sentence!";
String reversed = new StringBuilder(sentence).reverse().toString();
System.out.println(reversed); // Prints : !ecnetnes a si siht
Or use the append() method for building your new String object. This uses less memory than using a String because it is not creating a new String object each time you're looping :
String sentence = "this is a sentence!";
StringBuilder reversed = new StringBuilder();
for (int i = 0 ; i < sentence.length() ; i++){
reversed.append(sentence.charAt(sentence.length() - 1 - i));
}
System.out.println(reversed.toString()); // Prints : !ecnetnes a si siht
It maybe better to do it without any replacement, or for loop. It you create a char array from the string, reverse the array, then create a string from the reversed array this would do what you've asked without any moving parts or replacements. For example:
String hw = "hello world";
char[] hwChars = hw.toCharArray();
ArrayUtils.reverse(hwChars);
String wh = new String(hwChars);
System.out.println(wh);
Just split the String at each whitespace and put it in String array and then print the array in reverse order
public static void main(String[] args) {
String sentence = "this is a sentence!";
String[] reverseSentence = sentence.split(" ");
for (int i = reverseSentence.length-1; i >= 0; i--) {
System.out.print(" " + reverseSentence[i]);
}
}

String into char on 2D array (java)

I am trying to fill a 2D char array with 5 words. Each string must be split into single characters and fill one row of the array.
String str = "hello";
char[][] words = new char[10][5];
words[][] = str.toCharArray();
My error is at the 3rd line I don't know how to split the string "hello" into chars and fill only the 1st row of the 2-dimensional array
If you want the array to fill the first row, just asign it to the first row:
words[0] = str.toCharArray();
Since this will create a new array in the array, you should change the instantiation of words to this:
char[][] words = new char[5][];
Java has a String class. Make use of it.
Very little is known of what you want with it. But it also has a List class which I'd recommend as well. For this case, I'd recommend the ArrayList implementation.
Now onto the problem at hand, how would this code look now?
List<String> words = new ArrayList<>();
words.add("hello");
words.add("hello2");
words.add("hello3");
words.add("hello4");
words.add("hello5");
for (String s : words) {
System.out.println(s);
}
For your case if you are stuck with using arrays.
String str="hello";
char[][] words = new char[5][];
words[][] = str.toCharArray();
Use something along the line of
String str = "hello";
char[][] words = new char[5][];
words[0] = str.toCharArray();
for (int i = 0; i < 5; i++) {
System.out.println(words[i]);
}
However, why invent the wheel again? There are cases however, more can be read on the subject here.
Array versus List<T>: When to use which?

Remove chars from string in Java from file

How would I remove the chars from the data in this file so I could sum up the numbers?
Alice Jones,80,90,100,95,75,85,90,100,90,92
Bob Manfred,98,89,87,89,9,98,7,89,98,78
I want to do this so for every line it will remove all the chars but not ints.
The following code might be useful to you, try running it once,
public static void main(String ar[])
{
String s = "kasdkasd,1,2,3,4,5,6,7,8,9,10";
int sum=0;
String[] spl = s.split(",");
for(int i=0;i<spl.length;i++)
{
try{
int x = Integer.parseInt(spl[i]);
sum = sum + x;
}
catch(NumberFormatException e)
{
System.out.println("error parsing "+spl[i]);
System.out.println("\n the stack of the exception");
e.printStackTrace();
System.out.println("\n");
}
}
System.out.println("The sum of the numbers in the string : "+ sum);
}
even the String of the form "abcd,1,2,3,asdas,12,34,asd" would give you sum of the numbers
You need to split each line into a String array and parse the numbers starting from index 1
String[] arr = line.split(",");
for(int i = 1; i < arr.length; i++) {
int n = Integer.parseInt(arr[i]);
...
try this:
String input = "Name,2,1,3,4,5,10,100";
String[] strings = input.split(",");
int result=0;
for (int i = 1; i < strings.length; i++)
{
result += Integer.parseInt(strings[i]);
}
You can make use of the split method of course, supplying "," as the parameter, but that's not all.
The trick is to put each text file's line into an ArrayList. Once you have that, move forwars the Pseudocode:
1) Put each line of the text file inside an ArrayList
2) For each line, Split to an array by using ","
3) If the Array's size is bigger than 1, it means there are numbers to be summed up, else only the name lies on the array and you should continue to the next line
4) So the size is bigger than 1, iterate thru the strings inside this String[] array generated by the Split function, from 1 to < Size (this will exclude the name string itself)
5) use Integer.parseInt( iterated number as String ) and sum it up
There you go
Number Format Exception would occur if the string is not a number but you are putting each line into an ArrayList and excluding the name so there should be no problem :)
Well, if you know that it's a CSV file, in this exact format, you could read the line, execute string.split(',') and then disregard the first returned string in the array of results. See Evgenly's answer.
Edit: here's the complete program:
class Foo {
static String input = "Name,2,1,3,4,5,10,100";
public static void main(String[] args) {
String[] strings = input.split(",");
int result=0;
for (int i = 1; i < strings.length; i++)
{
result += Integer.parseInt(strings[i]);
}
System.out.println(result);
}
}
(wow, I never wrote a program before that didn't import anything.)
And here's the output:
125
If you're not interesting in parsing the file, but just want to remove the first field; then split it, disregard the first field, and then rejoin the remaining fields.
String[] fields = line.split(',');
StringBuilder sb = new StringBuilder(fields[1]);
for (int i=2; i < fields.length; ++i)
sb.append(',').append(fields[i]);
line = sb.toString();
You could also use a Pattern (regular expression):
line = line.replaceFirst("[^,]*,", "");
Of course, this assumes that the first field contains no commas. If it does, things get more complicated. I assume the commas are escaped somehow.
There are a couple of CsvReader/Writers that might me helpful to you for handling CSV data. Apart from that:
I'm not sure if you are summing up rows? columns? both? in any case create an array of the target sum counters int[] sums(or just one int sum)
Read one row, then process it either using split(a bit heavy, but clear) or by parsing the line into numbers yourself (likely to generate less garbage and work faster).
Add numbers to counters
Continue until end of file
Loading the whole file before starting to process is a not a good idea as you are doing 2 bad things:
Stuffing the file into memory, if it's a large file you'll run out of memory (very bad)
Iterating over the data 2 times instead of one (probably not the end of the world)
Suppose, format of the string is fixed.
String s = "Alice Jones,80,90,100,95,75,85,90,100,90,92";
At first, I would get rid of characters
Matcher matcher = Pattern.compile("(\\d+,)+\\d+").matcher(s);
int sum = 0;
After getting string of integers, separated by a comma, I would split them into array of Strings, parse it into integer value and sum ints:
if (matcher.find()){
for (String ele: matcher.group(0).split(",")){
sum+= Integer.parseInt(ele);
}
}
System.out.println(sum);

when using a array of strings in java, convert it to lowercase

I got a one dimensional array of strings in java, in which i want to change all strings to lowercase, to afterwards compare it to the original array so i can have the program check whether there are no uppercase chars in my strings/array.
i've tried using x.toLowercase but that only works on single strings.
Is there a way for me to convert the whole string to lowercase?
Kind regards,
Brand
arraylist.stream().map(s -> s.toLowerCase()).collect(Collectors.toList())
may help you
If you want a short example, you could do the following
String[] array = ...
String asString = Arrays.toString(array);
if(asString.equals(asString.toLowerCase())
// no upper case characters.
String array[]= {"some values"};
String str= String.join(',',array);
String array_uppercase[]=str.toLowerCase().split(',');
Just two line
String[] array = {"One", "Two"};
for(int i=0;i<array.length;i++){
if(!array[i].equals(array[i].toLowerCase()))
System.out.println("It contains uppercase char");
array[i] = array[i].toLowerCase();
}
for(int i=0;i<array.length;i++)
System.out.println(array[i]);
OUTPUT:
It contains uppercase char
It contains uppercase char
one
two
There's no easy way to invoke a method on every element of a collection in Java; you'd need to manually create a new array of the correct size, walk through the elements in your original array and sequentially add their lowercased analogue to the new array.
However, given what you're specifically trying to do, you don't need to compare the whole array at once to do this, and incur the cost of copying everything. You can simply iterate through the array - if you find an element which is not equal to its lowercase version, you can return false. If you reach the end of the array without finding any such element, you can return true.
This would in fact be more efficient, since:
you get to short-circuit further evaluation if you find an element that does have uppercase characters. (Imagine the case where the first element of a million-string array has an uppercase; you've just saved on a million calls to lowercase()).
You don't have to allocate memory for the whole extra array that you won't be using beyond the comparison.
Even in the best case scenario, your proposed scenario would involve one iteration through the array to get the lowercase versions, then another iteration through the array to implement the equals. Doing both in a single iteration is likely to be more efficient even without the possibility of short-circuiting.
Previously we used (In Java < 8)
String[] x = {"APPLe", "BaLL", "CaT"};
for (int i = 0; i < x.length; i++) {
x[i] = x[i].toLowerCase();
}
Now in Java8 :
x= Arrays.asList(x).stream().map(String::toLowerCase).toArray(String[]::new);
Two steps are needed:
Iterate over the array of Strings
Convert each one to lower case.
you can convert the array of strings to single string and then convert it into lower case and please follow the sample code below
public class Test {
public static void main(String[] args) {
String s[]={"firsT ","seCond ","THird "};
String str = " ";
for (int i = 0; i < s.length; i++) {
str = str + s[i];
}
System.out.println(str.toLowerCase());
}
}
import java.util.*;
public class WhatEver {
public static void main(String[] args) {
List <String> list = new ArrayList();
String[] x = {"APPLe", "BaLL", "CaT"};
for (String a : x) {
list.add(a.toLowerCase);
}
x = list.toArray(new String[list.size()]);
}
}
The following code may help you
package stringtoupercasearray;
import java.util.Scanner;
/**
*
* #author ROBI
*/
public class StringToUperCaseArray {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int size;
String result = null;
System.out.println("Please enter the size of the array: ");
Scanner r=new Scanner(System.in);
size=r.nextInt();
String[] s=new String[size];
System.out.println("Please enter the sritngs:");
for(int i=0;i<s.length;i++){
s[i]=r.next();
}
System.out.print("The given sritngs are:");
for (String item : s) {
//s[i]=r.nextLine();
System.out.print(item+"\n");
}
System.out.println("After converting to uppercase the string is:");
for (String item : s) {
result = item.toUpperCase();
System.out.println(result);
}
}
}
You can do it with a single line of code. Just copy and paste the following snippet, without any looping at all.
String[] strArray = {"item1 Iteme1.1", "item2", "item3", "item4", "etc"}//This line is not part of the single line (=D).
String strArrayLowerCase[] = Arrays.toString(strArray).substring(1)
.replace("]", "").toLowerCase().split(",");
Happy String Life. =D

Categories