How to display the total length of strings in a string array? - java

My code:
public class array3 {
/**
* #param args
*/
public static void main(String[] args) {
String[] names = {"Einstein", "Newton", "Copernicus", "Kepler"};
for(int i = 0; i < names.length; i++){
System.out.println(names[i]);
}
}
}
I need to write a code that displays the total length of all the strings in the array I have declared(names). The only thing that comes in my mind for now is to use "names.length" but this will only give the number of elements in the String, not the actual length of the Strings.

Simply put, It can be done by:
int s=0; // A variable to store the length
for(int i = 0; i < names.length; i++){
s+=names[i].length(); // add length of each String
}
System.out.println(s); // Print `s`.

If you are using Java 8+, you might use Stream.mapToInt(ToIntFunction<? super T>) and IntStream.sum() like
String[] names = { "Einstein", "Newton", "Copernicus", "Kepler" };
System.out.println(Stream.of(names).mapToInt(String::length).sum());
If you want the length of each String you might use a lambda to display the String and its' length like
Stream.of(names).forEach(s -> System.out.printf("%s %d%n", s, s.length()));

Related

How to remove certain elements from my array in my Java code

I am working on the following coding prompt for my class:
Your task is to write a method with the following signature:
public static String[] removeFromArray(String[] arr, String toRemove)
The method should return a string array that has the same contents as arr, except without any
occurrences of the toRemove string. For example, if your method is called by the code below
String[] test = {“this”, “is”, “the”, “example”, “of”, “the”, “call”};
String[] result = removeFromArray(test, “the”);
System.out.println(Arrays.toString(result));
it should generate the following output:
[this, is, example, of, call]
Note: Your method will be passed values for arr and toRemove by the testing program – you should not
read these values in from the user inside your method. Also, you must write this method with the
signature requested above in order to receive credit. You do not need to write the code that calls the
method – only the method itself.
Hint: Because you must specify the length of an array when you create it, you will likely need to make
two loops through the input array: one to count the number of occurrences of the toRemove string so
that you can create the new array with the proper size and a second to copy all of the other strings to the new array.
I have everything working in my code but the last part where I have to print out the new array does not work, I know I have make it smaller so it will print out properly, but I can't get that part to work. I know I have to get rid of the null, but I don't know how. Also my code has to work for any array not just the test case I have. Some help or advice would really be nice. Thank you very much!!! :)
Here is my code:
public static void main(String[] args) {
String[] test = {"this", "is", "the", "example", "of", "the", "call"};
String[] remove = removeFromArray(test, "the");
System.out.println(Arrays.toString(remove));
}
public static String[] removeFromArray(String[] arr, String toRemove) {
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(toRemove)) {
count++;
}
}
String[] result = new String[arr.length - count];
//for (int i = 0; i < arr.length; i++) {
// if(!arr[i].equals(toRemove)){
// result[].equals(arr[i]);
//}
//}
return result;
}
you approach looks ok, it looks like the commented code yor are trying to assign the new array with the wrong emthod
you should use result[i] = arr[i] ; instead of result[].equals(arr[i]);
do at the end:
String[] result = new String[arr.length - count];
int k = 0;
for (int i = 0; i < arr.length; i++) {
if(!toRemove.equals(arr[i])){
result[k] = arr[i];
k++;
}
}
return result;
Your last part should be assigning the value to the array one by one.
int j = 0;
for (int i = 0; i < arr.length; i++) {
if(!toRemove.equals(arr[i])){
result[j++] = arr[i];
}
}
It's asking you to return a new String array which excludes the given word. Loop through the array and add word which does not equal to the given word.
public static String[] removeFromArray(String[] arr, String toRemove){
ArrayList<String> words = new ArrayList<>();
for(String s : arr)
if(!s.equals(toRemove))
words.add(s);
return words.toArray(new String[0]);
}
Since array size cannot be changed after being created, use an ArrayList to store the words, then return as an array.
I know you're new to programming itself, so the solutions given are perfectly fine.
However, using Java, you'd usually use the libraries; in this case, the Collections library. If you're using Java 8, this is how you would do it:
public static String[] removeFromArray(String[] arr, String toRemove) {
// create a List and fill it with your items
ArrayList<String> list = new ArrayList();
Collections.addAll(list, arr);
// remove the items that are equal to the one to be removed
list.removeIf(s -> toRemove.equals(s));
// transfer back to array
return list.toArray(new String[list.size()]);
}
Then, there are Java 8 Streams, which would make this
public static String[] removeFromArray(String[] arr, String toRemove) {
return Arrays.stream(arr) // create stream from array
.filter(s -> !toRemove.equals(s)) // filter out items
.toArray(String[]::new); // create array from stream
}

Count how many times a letter appears in 2d array JAVA

So I basically have an array that looks like this:
BG6001;1193;M;63;B+
BG6001;1124;M;41;C
BG6001;1121;F;FA;FA
BG6001;1143;M;26;FA
BG6001;1157;F;74;A
And what I've been trying to do is to count how many times the letter "M" appears in it, and add it into a counter
Any ideas?
What I have tried so far:
for (int i=0; i<name.length(); i++) {
if (name.charAt(i)=='M' ) counter++;
}
System.out.println("the string contains " + count + " times the letter M")
You should probably use a foreach loop. Try implementing something like this:
int counter=0;
String[][] array = something;
for(String[] subArray : array)
for(String string : subArray)
if(string.toLowerCase().equals("m"))
counter++;
//Counter has the value of the amount of 'm's in the array
#mike fischer please check the below code whoich gives you the count of "M" in an Array.
public class Arraycount {
public static void main(String args[]){
String[] a=new String[5];
a[0]="BG6001;1193;M;63;B+";
a[1]="BG6001;1124;M;41;C";
a[2]="BG6001;1121;F;FA;FA";
a[3]="BG6001;1143;M;26;FA";
a[4]="BG6001;1157;F;74;A";
int count=0;
for(int i=0;i<=a.length-1;i++){
for(int j=0;j<=a[i].length()-1;j++){
char c=a[i].charAt(j);
if(c=='M'){
count++;
}
}
}
System.out.println("Number of M present in an array is "+count);
}
}
My answer is very similar to 7H3_H4CK3R's answer with some variation. Specifically, if a particular letter (in this case, "M") could appear anywhere in the string, you can do the following (and I apologize for using C# rather than Java syntax here, I'm not sitting in front of a Java compiler, but hopefully the differences won't be too difficult to follow):
private static int Count(string[][] data, char letterToFind)
{
int count = 0;
// Loop over each array
foreach (string[] array in data)
{
// Each array is a collection of strings
foreach (string str in array)
{
// Loop through the characters in each string
for (int i = 0; i < str.Length; i++)
{
if (str[i] == letterToFind)
{
count++;
}
}
}
}
return count;
}
Alternatively, if you're looking for something where the entire string is "M" 7H3_H4CK3R's answer should do the trick.

Parsing a string and returning an array

Heres my code that takes a string and returns an array of the ascii values for each character in the array in order. Compile error is 'array required, but java.lang.String found'
public class Q1E {
int[] stringToCodes(String characters){
int characterLength= length(characters);
int[] array=new int[characterLength];
for(int i=0;i<characterLength;i++) {
array[i] =(int) characters[i];
}
}
}
You can't use array syntax on a String, use character.charAt(i)instead. Also, you need to return the array at the end.
Java uses Unicode/UTF-16 for strings, not ASCII.
If want to restrict your method to processing characters in the ASCII range, it should throw an exception when it encounters one outside that range.
If you want a sequence of "character codes" (aka codepoints), you have to use the String.codePointAt() at method. Because String holds a counted sequences of UTF-16 code-units and there might be one or two code-units per codepoint, you only know that String.length() is an upper bound of the number of codepoints in advance.
public class Q1E {
int[] stringToCodes(String s) {
int[] codepoints = new int[s.length()]; // there might be fewer
int count = 0;
for(int cp, i = 0; i < s.length(); i += Character.charCount(cp)) {
cp = s.codePointAt(i);
// for debugging, output in Unicode stylized format
System.out.println(String.format(
cp < 0x10000 ? "U+%04X" : "U+%05X", cp));
codepoints[count++] = cp;
}
int[] array = java.util.Arrays.copyOf(codepoints, count);
return array;
}
}
Try it with this Wikipedia link on an English word:
stringToCodes("http://en.wikipedia.org/wiki/Résumé");
Your code appears to have a few bugs, it's String#length() and I would suggest you add a null check. Finally (since characters isn't an array), I think you want to use String#charAt(int)
int[] stringToCodes(String characters) {
int characterLength = 0;
if (characters != null) {
characterLength = characters.length();
}
int[] array = new int[characterLength];
for (int i = 0; i < characterLength; i++) {
array[i] = characters.charAt(i);
}
return array;
}
Of course, you could shorten it with a ternary
int characterLength = (characters != null) ? characters.length() : 0;
int[] array = new int[characterLength];
try this:
public class Test {
public static void main(String[] args) {
int []ascii=stringToCodes("abcdef");
for(int i=0;i<ascii.length;i++){
System.out.println(ascii[i]);
}
}
public static int [] stringToCodes(String characters){
int []ascii=new int[characters.length()];
for(int i=0;i<characters.length();i++){
ascii[i]=(int)characters.charAt(i);
}
return ascii;
}
}

Java method argument in calling and caller methods

Just simple reverse string method.
FYI, correct methods are reverseString1 and reverseString2,
but revereStirng3() doesn't give me correct output.
I think this is because of method args and return values are stored in the Stack and related with this concept. But I don't clearly understand why revereStirng3() doesn't work correctly.
Please let me know whey this is not working.
This is what I understand, and please correct me if I'm wrong.
1. main() calls revereStirng3(A) where this passing argument array A is stored in the stack frame for the main().
revereStirng3(char[] A) where this passed argument array A is stored in revereStirng3's method frame which means main's A[] is copied to revereStirng3's stack frame's method argument A[].
After reverse, revereStirng3 creates new String(A) for return String.
Then, I thought, in the main, returned new String(A) is correctly print reversed string, but actually not.
// Given a string "abcdef", reverse it. so output should be "fedcba"
import java.util.*;
public class ReverseString {
static String revereStirng3(char[] A) {
int n = A.length;
for(int i=0; i<n/2; i++) {
char temp = A[n-i-1];
A[n-i-1] = A[i];
A[i] = temp;
}
return new String(A);
}
static void revereStirng1(char[] A) {
int n = A.length;
for(int i=0; i<n/2; i++) {
char temp = A[n-i-1];
A[n-i-1] = A[i];
A[i] = temp;
}
}
static String revereStirng2(String str) {
char[] A = str.toCharArray();
int n = A.length;
for(int i=0; i<n/2; i++) {
char temp = A[n-i-1];
A[n-i-1] = A[i];
A[i] = temp;
}
return String.valueOf(A);
}
public static void main(String[] args) {
String s = "abcdef";
char[] A = s.toCharArray();
System.out.print( revereStirng3(A) + "\n" ); **// print out "abcdef"**
System.out.println( "" );
revereStirng1(A); // print out "fedcba"
for(int i=0; i<A.length; i++)
System.out.print( A[i] );
System.out.println( "" );
System.out.print( revereStirng2(s) + "\n" ); // print out "fedcba"
System.out.println( "" );
}
}
Ok, given that zenbeni has got the real results, here is what is happening.
An array in Java is an object, so in revereString1 and revereString3 you get a copy of the reference to the array. So, your changes modify the original array, which (after the first method execution) has been reversed. Of course, the second execution reverses it again, so you get the reverse of the reverse, which is the original String.
Try using a new, locally defined array to create the reversed String and everything will work fine.
From apache commons:
StringUtil.reverse(str);
I have copied your method and executed it
System.out.println(revereStirng3("abcdef".toCharArray()));
on the result was
fedcba.
The problem is located in the main function:
public static void main(String[] args) {
String s = "abcdef";
char[] A = s.toCharArray();
System.out.println( revereStirng3(A)); // print out "abcdef"**
revereStirng1(A);
System.out.print(Arrays.toString(A)); // print out "fedcba"
System.out.println(revereStirng2(s)); // print out "fedcba"
}
Your comments do not show the true.
The valid output for it would be
fedcba
[a,b,c,d,e,f]
fedcba
And this is because you operate on the same array for three test cases. In the second step you pass allready reversed array as input. This results that the order has not changed.

java tips (converting string to array)

there. I faced a bit trouble with java programming
**Could someone give me a hint which of the method use in order to
string= "23578893762467290465" convert to array y= [2,3,5,7]....??**
I mean, that for example y[0]=2, y[1]=3, y[2]=5....
Thanks in advance
String.toCharArray()
From the official documentation:
It returns a newly allocated character array whose length is the
length of this string and whose contents are initialized to contain
the character sequence represented by this string.
Convert String to an integer array.
String string= "23578893762467290465";
int[] intArray = new int[string.length()];
for(int i = 0; i<string.length(); i++){
intArray[i] = Integer.parseInt(String.valueOf(string.charAt(i)));
}
public class StringToInt{
public int[] convert(String arg){
char[] characters = arg.toCharArray();
int[] integers = new int[arg.length()];
for ( int i = 0; i < characters.length; i++ )
integers[i] = Character.getNumericValue(characters[i]);
return integers;
}
private void prettyPrint(int[] result){
System.out.print("array: ");
for(int i : result){
System.out.print(i+" ");
}
}
public static void main(String[]args){
StringToInt converter = new StringToInt();
int[] result = converter.convert(args.length > 0?args[0]: "23578893762467290465" );
converter.prettyPrint(result);
}
}
ok, people beat me to it. But this'll work.
in essence:
Convert to char-array.
call Character.getNumericValue() for each character.
Another way may be:
int[] arr = new int[string.length()];
for(int i = 0; i<string.length(); i++){
arr[i] = Character.getNumericValue(string.charAt(i));
System.out.println(arr[i] + " ") ;
}

Categories