any other way to find char array length? - java

public static int getLenth(char[] t)
{
int i=0;
int count=0;
try
{
while(t[i]!='\0')
{
++count;
i++;
}
return count;
}
catch(ArrayIndexOutOfBoundsException aiobe)
{
return count;
}
}
This method returns length of charArray. But my question is, is there is some other "ways" to find the length of charArray without using this try, catch statements & all ??
Thanks in advance :)

you can use length property of char array
simple example
char [] cd={'a','b'};
System.out.println(cd.length);
output
2

You can/should use the built-in length property to determine the size of any array.
int len = t.length;
You can learn more about arrays from here.

If you want to write your own custom code for the length property and also want to check the length of the char array then must go for StringBuffer , and append one by one character from the character array to the StringBuffer and check the no of character by using looping till the space character i.e " " as because String buffer has extra capacity of 16 character so there must be some space available after appending data from char array to StringBuffer.

Related

Why is this code not executing properly? Longest substring problem

So I'm trying to solve the Longest Substring Without Repeating Character problem in a webpage and when I'm trying to upload it it will show me this bug:
class Solution {
public int lengthOfLongestSubstring(String s) {
HashSet<Character> hash = new HashSet<>();
int count = 0, finalCount = 1;
char prevChar = s.charAt(0);
hash.add(prevChar);
for (int i = 1; i < s.length(); i++)
{
char character = s.charAt(i);
if (!hash.contains(character)){
hash.add(character);
count++;
if (count > finalCount) finalCount = count;
}
else{
hash.clear();
hash.add(character);
count = 1;
}
prevChar = character;
}
return finalCount;
} }
Is there anything wrong with it?
If not, do you think my algorithm was efficient? I can't compare its performance since the webpage won't let me upload it.
You call s.charAt(0) in line 5. I imagine they pass in the empty string as a test case and you are getting an out of bounds exception. Prior to line 5 add a check to see if the string length is 0 and if it is return 0.
According to the error description it's doing a dummy-spit at line 5 of the Solution class.
Based on the picture that's:
char prevChar = s.charAt(0);
The error is ArrayIndexOutOfBounds which generally indicates you tried to get more out of something than was actually there (e.g. running over the end of an array).
Here I'd suggest maybe putting in some System.out.println lines at line 3 to sanity check the method parameter, e.g.:
(a) if the input String s is null
or
(b) if the input String s is empty (e.g. "")
charAt(0) will get the first character, but if there are zero characters then trying to get the 1th character is an error, no?
NB: something like this:
System.out.println("Input was :" + s + ":");
Will show both of those conditions, as either:
Input was ::
for an empty String
Input was :null:
for a null String

Substring a string based on presence of a character

I have a string: LOAN,NEFT,TRAN. I want to substring the string based on getting a , during traversing the string. So I tried to first get a count for how many , are there. but not sure what function to user to get what I want. Also this should be dynamic, meaning I should be able to create as many substrings as required based on number of ,s. I tried the following code:
package try1;
public class StringTest {
public static void main(String[] args) {
String str="LOAN,NEFT,TRAN";
int strlen=str.length();
int count=0;
for(int i=0;i<strlen;i++)
{
if(str.contains("'"))
count++;
}
System.out.println(""+count);
for (int j=0;j<count;j++)
{
//code to create multiple substrings out of str
}
}
}
But I do not think contains() is the function I am looking for because value of count here is coming 0. What should I use?
Your code doesn't actually count the , characters because 1) contains doesn't take into account your loop variable 2) it's searching for ', not ,
Assuming you want to work at a low level rather than using high level functions like .split(), then I'd recommend the following.
for(char c : str.toCharArray()) {
if (c == ',') {
count++;
}
}
You can use split to get substrings directly:
String[] substrings = str.split(",");
Is this what you want as an output: (shown below)?
["LOAN", "NEFT", "TRAN"] // Array as an output
Or to just get the count of the splitting char, you can use the same line as above with this:
int count = substrings.length - 1;

memory leak issue on using java substring method

I have looked through all the memory leak solutions for java substring method. I still get the out of memory error due to this issue. I have an arraylist of string which are of length 1000-3500. i index them and store them. The issue is each string needs to be run through loop to store all possible varying lengths of same string. To do this, i use for loop and substring method. and this method causes the memory leak problem.
A sudo code of what i have done:
for(int i=0;i<str.length;i++)
{
//create substring and index it
str.substring(0,(str.length()-i));
}
str: string. and this above loops runs till all the string within the arraylist are indexed. I tried to fix the leak by,
1.
for(int i=0;i<str.length;i++)
{
//create substring and index it
new String(str.substring(0,(str.length()-i)));
}
2.
for(int i=0;i<str.length;i++)
{
//create substring and index it
new String(str.substring(0,(str.length()-i)).intern());
}
3.
for(int i=0;i<str.length;i++)
{
//create substring and index it
new String(str.substring(0,(str.length()-i))).intern();
}
Still i have the issue. My java version is: 1.7.0_17.
Edit:
I understand this is not a memory leak problem from the comments. I am indexing some continuous strings. Say for example,
String s= abcdefghijkl;
i want index each string as :
abcdefghjk
abcdefghj
abcdefhg
abcdefh
abcdef
abcde
abcd
..
..
a
To perform this,i get a string,then perform substring operation,get that string and index them.
There is no leak.
Please note that you're creating a huge amount of String objects. If a String has a length of 1000 characters you're creating 1000 objects.
Is it really needed to create so many String objects? Would it be possible for example to use a char[] to achive what you want?
There are 2 things:
First: ".intern()" keeps the string in an internal cache that is usually not garbage collected - please don't use it if you're not 100% sure why you are using it.
Second: there is a constructor from String taking char[] like this:
final char[] chars = str.toCharArray ();
for(int i=0;i<chars.length;i++)
{
//create substring and index it
new String(chars, 0, chars.length-i);
}
-> this is also more efficient (in terms of speed)
This problem fixed in the JDK 1.7 by returning the new copy of character array.
public String(char value[], int offset, int count) {
//check boundary
// It return new copy on array.
this.value = Arrays.copyOfRange(value, offset, offset + count);
}
public String substring(int beginIndex, int endIndex) {
//check boundary
int subLen = endIndex - beginIndex;
return new String(value, beginIndex, subLen);
}
http://javaexplorer03.blogspot.in/2015/10/how-substring-memory-leak-fixed-in-jdk.html?q=itself+implements+Runnable

Tallying each character

NOTE: For array of counters, one for each UTF-16 character, tallies usage of each char.
For a program I am writing, im trying to tally each character in a specific word. Thus far, i have,
public void tally(String word)
{
if ((word == null) || (word.length() == 0))
return;
(Insert here)
}
For where I have "Insert here" is where i am trying to tally each character in a specific word. Does anyone know simple way of doing it?
Create a map
Start with the 1st char For each character, check if the character key exists in the map, if yes, increase the value of the key by one.
If it doesn't exist, insert the character as key and value as one. when done, print the map.
This look like homework so I'll give some brief pointers
You can split a string into characters with toCharArray
You can iterate over an array with for each
You can store values in an HashMap
public void tally(String word)
{
int count;
if (word == null)
{
return count;
}
else
{
char[] ca;
ca = word.toCharArray();
for(int i = 0; i < ca.length; i++)
{
count++;
}
return count;
}
This will show you how many letters are in the word in total. I think, from this, you can do the rest.

How is this program coming along?

Instructions:
Write a program that will read a line of text that ends
with a period, which serves as a sentinel value. Display all the
letters that occur in the text, one per line and in alphabetical
order, along with the number of times each letter occurs in the text.
Use an array of base type int of length 26 so that the element at
index 0 contains the number of as. and index 1 contain number of bs etc.
package alphabetize;
import java.util.*;
public class Alphabetize
{
private static void number(String s)
{
int[] array = new int[26];
s = s.toUpperCase();
System.out.println(s);
for (int i = 0; i < s.length(); ++i)
{
if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')
{
++array[s.charAt(i) - 'A'];
}
}
for (int i = 0; i < 26; ++i)
{
System.out.println("|" + (char) ('A' + i) + "|" + array[i] + "|");
}
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String aString = ".";
while (true)
{
System.out.println("Please enter sentence with a period to end");
aString = keyboard.nextLine();
if (".".equals(aString))
{
System.exit(0);
}
number(aString);
}
}
}
Still having problem with the period thing.. it does not seem to work the way i did it.
Considering this is a homework and instructions are very specific, you should read the text character by character instead of using built-in functions
If your text file was something like
abcabca.
The output should be something a appears three times, b appears two times etc etc.
So your algo should be something like
Read next character
If char is period goto 5
If char is space goto 1.
If char is between a <-> z. update the counter in arr[0..25] and goto 1
output arr[0..25] one per line
Was it mandated that this assignment is done in Java? The whole idea of a "sentinal character" rather than just using a line terminator is pretty bizarre.
Anyway, you can achieve the behaviour you want by setting the delimiter of Scanner:
keyboard.useDelimiter("\\.");
As for the looping, a big hint is this:
int[] counts;
counts[chars[0] - 'a'] = counts[chars[0] - 'a'] + 1;
or simply
counts[chars[0] - 'a']++;
I'll leave it up to you to include that in a loop.
Edit
If you are looking for character-at-a-time input, I would suggest you use an InputStreamReader instead of Scanner for your input. Here's a basic skeleton of what that looks like:
Reader reader = new InputStreamReader(System.in);
while (true) {
int nextInput = reader.read();
if (nextInput == -1) {
System.out.println("End of input reached without sentinal character");
break;
}
char nextChar = (char) nextInput;
//deal with next character
}
Still, read() will typically block until either the end of input is reached (CTRL-D or CTRL-Z from most consoles) or a new line is sent. Thus the sentinal character is of limited use since you still have to do something after typing ".".
You have to check whether period is there at the end or not. So the last character should be '.'.
Then take the length of string before last '.'.
For the counting part create an array like u are doing :
int [] name = new int[26]
where each index starting from 0, 25 corresponds to 'a' till 'z'.
Now you put the string characters in a loop and have to check what that character is like :
if its a 'a' : increase the value at index 0 by 1.
if its a 'd' : increase the value at index 3 by 1.
like wise.
later you display the whole array with a, z along with indexes from 0 till 25.
Suggestion: If its not required to use an array, and you can use any other data-structure you can implement the same in a HashMap very easily. by keeping 'a', 'z' as the keys and count as the corresponding values. and then retrieving and showing the values will also be easier.
You need an int array (e.g., int[] counts = new int[26];) After you read the input line, examine it character by character in a loop. If the character is a not period, then increment the appropriate element of the counts array. (If the character is a, then increment counts[0]; if it is b, increment counts[1]; etc. Hint: you can subtract a from the character to get the appropriate index.) When you find a period, exit the loop and print the results (probably using a second loop).

Categories

Resources