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

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

Related

Number of words in a string that are not in an array of strings

I want to create a method that returns the number of words in a string that have no occurrences of words in the array of strings. I want to implement this logic only using anything in the java.lang package.
public int count(String a, String[] b) {
}
E.g.
count(" hey are you there ", new String[]{ "are", "i", "am"})
would return 3 as there is the word "are" in the string.
First off, I think I have to use the string.split function to convert the string to an array of strings. Any ideas?
You could simply do something like:
public int count(String a, String[] b) {
int count = b.length;
for(String s : b) if(a.contains(s)) count--;
return count;
}
EDIT: I might have been confused, I thought you wanted the # of strings in b not in a (in your example it would still be 3). In that case, from your example, split seems inconvenient unless you use regex, so you could create a String[] using Scanner:
public int count(String a, String[] b) {
ArrayList<String> words = new ArrayList<String>();
Scanner scan = new Scanner(a);
while(scan.hasNext()) words.add(scan.next());
int count = words.size();
for(String s : words) if(/*b contains s*/) count--;
return count;
}
Follow the steps to complete the task.
Use StringTokenizer to tokenize the String a.
Convert String Array b to Collection, so that you can check if it contains the given token.
Use loop to get next token from StringTokenizer and check if it contains in List.
-
Try below code, it'll work.
EDIT : Using java.util package.
public int count(String a, String[] b) {
java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(a);
java.util.List bList = java.util.Arrays.asList(b);
int tokens = tokenizer.countTokens();
int counter = tokens;
for(int i=0;i<tokens;i++) {
String token = tokenizer.nextToken().trim();
if(bList.contains(token)) {
counter--;
}
}
return counter;
}
By using this, you can get the counter in just one for loop.
EDIT :: Using java.lang package only.
public int count(String a, String[] b) {
String[] words = a.split(" ");
int tokens = words.length;
int wordCount = 0;
int counter = 0;
for(int i=0;i<tokens;i++) {
String token = words[i].trim();
if(token.length() <= 0) {
continue;
}
wordCount++;
for(String bItem : b) {
if(bItem.equals(token)) {
counter++;
break;
}
}
}
return wordCount - counter;
}
You logic should go somewhat like this:
Split a, right. Now you have a list of words. In a real life, you should probably also try to clarify the requirement—what exactly is a “word”? A reasonable assumption is that it's a sequence of non-whitespace characters, but could be something different (for example, a sequence of letters).
Iterate over a and check whether each word is in b. If it isn't, increment your counter. But every check is a linear search in b, leading to the total complexity of O(nm), so...
Before iterating, convert b into a HashSet. This is a linear operation, but then your main loop will also become a linear operation, therefore the total complexity will be O(m + n).
If you have to do this thing repeatedly for different strings, but the same word list, consider creating a WordCounter class so you only have to create the HashSet once in the constructor.

Java - Error trying to print an array made of 2 appended arrays

I am studying in prevision of my exam of Software Programming. Here I am trying to append 2 arrays but what I get printed is:
[I#17dfafd1
here is the code:
package examPreparation2014;
public class FirstExercise {
public static void main(String[] args){
int[] first = {1,2,3};
int[] second = {4,5,6};
System.out.print(FirstExercise.concatenator(first, second));
}
public static int[] concatenator(int[] first, int[] second){
int[] concatenatedArray = new int[first.length + second.length];
for (int i = 0; i<first.length ; i++){
concatenatedArray[i] = first[i];
}
for (int i=0; i<second.length; i++){
concatenatedArray[i+first.length] = second[i];
}
return concatenatedArray;
}
}
PS: this is an exam on paper, therefore I cannot import libraries :-)
Arrays are Objects too, but they don't override Object's toString() method.
In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
That explains the strange-looking output you've received.
Try Arrays.toString:
The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space).
System.out.print(Arrays.toString(FirstExercise.concatenator(first, second)));
In your case it's printing the default implementation of toString() of object class.
Simply use for each loop to print all the values of the array.
for (int i : concatenator(first, second)) {
System.out.println(i);
}
A simpler way to append two arrays using org.apache.commons.lang.ArrayUtils
int[] both = ArrayUtils.addAll(first, second);

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);

Determining if a given string of words has words greater than 5 letters long

So, I'm in need of help on my homework assignment. Here's the question:
Write a static method, getBigWords, that gets a String parameter and returns an array whose elements are the words in the parameter that contain more than 5 letters. (A word is defined as a contiguous sequence of letters.) So, given a String like "There are 87,000,000 people in Canada", getBigWords would return an array of two elements, "people" and "Canada".
What I have so far:
public static getBigWords(String sentence)
{
String[] a = new String;
String[] split = sentence.split("\\s");
for(int i = 0; i < split.length; i++)
{
if(split[i].length => 5)
{
a.add(split[i]);
}
}
return a;
}
I don't want an answer, just a means to guide me in the right direction. I'm a novice at programming, so it's difficult for me to figure out what exactly I'm doing wrong.
EDIT:
I've now modified my method to:
public static String[] getBigWords(String sentence)
{
ArrayList<String> result = new ArrayList<String>();
String[] split = sentence.split("\\s+");
for(int i = 0; i < split.length; i++)
{
if(split[i].length() > 5)
{
if(split[i].matches("[a-zA-Z]+"))
{
result.add(split[i]);
}
}
}
return result.toArray(new String[0]);
}
It prints out the results I want, but the online software I use to turn in the assignment, still says I'm doing something wrong. More specifically, it states:
Edith de Stance states:
⇒     You might want to use: +=
⇒     You might want to use: ==
⇒     You might want to use: +
not really sure what that means....
The main problem is that you can't have an array that makes itself bigger as you add elements.
You have 2 options:
ArrayList (basically a variable-length array).
Make an array guaranteed to be bigger.
Also, some notes:
The definition of an array needs to look like:
int size = ...; // V- note the square brackets here
String[] a = new String[size];
Arrays don't have an add method, you need to keep track of the index yourself.
You're currently only splitting on spaces, so 87,000,000 will also match. You could validate the string manually to ensure it consists of only letters.
It's >=, not =>.
I believe the function needs to return an array:
public static String[] getBigWords(String sentence)
It actually needs to return something:
return result.toArray(new String[0]);
rather than
return null;
The "You might want to use" suggestions points to that you might have to process the array character by character.
First, try and print out all the elements in your split array. Remember, you do only want you look at words. So, examine if this is the case by printing out each element of the split array inside your for loop. (I'm suspecting you will get a false positive at the moment)
Also, you need to revisit your books on arrays in Java. You can not dynamically add elements to an array. So, you will need a different data structure to be able to use an add() method. An ArrayList of Strings would help you here.
split your string on bases of white space, it will return an array. You can check the length of each word by iterating on that array.
you can split string though this way myString.split("\\s+");
Try this...
public static String[] getBigWords(String sentence)
{
java.util.ArrayList<String> result = new java.util.ArrayList<String>();
String[] split = sentence.split("\\s+");
for(int i = 0; i < split.length; i++)
{
if(split[i].length() > 5)
{
if(split[i].matches("[a-zA-Z]+"))
{
result.add(split[i]);
}
if (split[i].matches("[a-zA-Z]+,"))
{
String temp = "";
for(int j = 0; j < split[i].length(); j++)
{
if((split[i].charAt(j))!=((char)','))
{
temp += split[i].charAt(j);
//System.out.print(split[i].charAt(j) + "|");
}
}
result.add(temp);
}
}
}
return result.toArray(new String[0]);
}
Whet you have done is correct but you can't you add method in array. You should set like a[position]= spilt[i]; if you want to ignore number then check by Float.isNumber() method.
Your logic is valid, but you have some syntax issues. If you are not using an IDE like Eclipse that shows you syntax errors, try commenting out lines to pinpoint which ones are syntactically incorrect. I want to also tell you that once an array is created its length cannot change. Hopefully that sets you off in the right directions.
Apart from syntax errors at String array declaration should be like new String[n]
and add method will not be there in Array hence you should use like
a[i] = split[i];
You need to add another condition along with length condition to check that the given word have all letters this can be done in 2 ways
first way is to use Character.isLetter() method and second way is create regular expression
to check string have only letter. google it for regular expression and use matcher to match like the below
Pattern pattern=Pattern.compile();
Matcher matcher=pattern.matcher();
Final point is use another counter (let say j=0) to store output values and increment this counter as and when you store string in the array.
a[j++] = split[i];
I would use a string tokenizer (string tokenizer class in java)
Iterate through each entry and if the string length is more than 4 (or whatever you need) add to the array you are returning.
You said no code, so... (This is like 5 lines of code)

Java character array initializer

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 + " ");

Categories