can anyone tell me , where can I find the logic of java in-built String methods like length() , tocharArray(), charAt() , etc... I have tried decompiler on String.class but found no logic their.
I want to a code to count the number of characters of a String without using any in-built String class but I am unable to crack the idea of how to break String into set of characters without using String in-built method..
e.g. String str = "hello";
how to convert this String into
'h' , 'e' , 'l' , 'l' , 'o'
and this is not any homework assignment...
please help
with regards,
himanshu
Built-in libraries source code is available with JDK.
The JDK folder would contain src.zip which contain the sources for the built-in libraries.
I always used http://grepcode.com. It usually has source code of methods/objects I'm looking for.
Here is GC for String class String.length()
EDIT:
As for your second question, how to calculate String length. I would use String.toCharArray(). I hope you can calculate length of an array.
You can view OpenJDK source code online. Make sure you're looking at the right version of the code (library version and revision).
For example, here's the code of toCharArray() of jdk8:
public char[] toCharArray() {
// Cannot use Arrays.copyOf because of class initialization order issues
char result[] = new char[value.length];
System.arraycopy(value, 0, result, 0, value.length);
return result;
}
Here's charAt(int index):
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
You can find the source code of String class here.
Whole string data is kept in a private char array field.
length() is just:
public int length()
{
return this.value.length;
}
And charAt(int) isn't much more complicated:
public char charAt(int paramInt)
{
if ((paramInt < 0) || (paramInt >= this.value.length)) {
throw new StringIndexOutOfBoundsException(paramInt);
}
return this.value[paramInt];
}
The method you are looking for separation String chars is toCharArray()
If you want to decomplie .class files try using: http://jd.benow.ca/
It has both GUI application and Eclipse IDE plugin.
You can't work with a String without using - directly or indirectly - its methods. For example, you can iterate over string characters using charAt(int index) or create a StringBuilder(String s) (which calls String.length() internally).
Related
I'm writing a code that would replace the lettering in a string with another letter. However, my current assignment wants the code in a particular format. I attempted the code below:
public String replaceLetter(String word, char letterToReplace, char replacingLetter)
{
letterToReplace = Character.toString(letterToReplace);
replacingLetter = Character.toString(replacingLetter);
word = word.replaceAll(letterToReplace, replacingLetter);
return word;
}
Please excuse any inefficiencies in the coding as I am still relatively new to programming in general. I also recently got into chars and strings more intensely,so there is much I do not know in terms of some of the rules or traits pertaining to them. Are the errors in my code illogical? The IDE I am currently using is an online one that has the sole purpose of collecting my assignment for grading. Whenever I compile the code above, it gives me errors such as a missing return statement, so I would not count it as reliable. The IDE itself is extremely limited, and cannot compile things such as switch statements, so I'd prefer if I could keep it as simple as possible. However, I have found that the IDE will recognize most correct coding. I did try to attempt the coding with a for statement:
public String replaceLetter(String word, char letterToReplace, char replacingLetter)
{
for (int i = 0; i < word.length(); i++)
{
char ca = word.charAt(i);
if (ca == letterToReplace)
{
word = (word.substring(0,i)+ replacingLetter + word.substring(i+1));
}
}
return word;
}
But I also ran into errors. Any help in correcting my syntax would be appreciated.
You're trying to assign your Strings created with Character.toString to your existing chars, then you're passing those chars into the replaceAll function (which doesn't accept chars, it needs Strings). Try changing your code to this:
public String replaceLetter(String word, char letterToReplace, char replacingLetter)
{
String letterToReplaceAsString = Character.toString(letterToReplace);
String replacingLetterAsString = Character.toString(replacingLetter);
word = word.replaceAll(letterToReplaceAsString, replacingLetterAsString);
return word;
}
Edit: As ajb pointed out, you could also call replace (instead of replaceAll) passing in your original char perimeters, and skip the step of assigning your Strings. Note that replace will still replace all occurrences of the char:
return word.replace(letterToReplace, replacingLetter);
Your letterToReplace and replacingLetter variables are character type and you are assigning String to them as Character.toString method returns string.
Change the variable type to String and you will be good to go.
Trying to implement contains() method without using built-in method contains().
Here is my code:
public static boolean containsCS(String str, CharSequence cs) {
//char[] chs = str.toCharArray();
boolean result = false;
int i=0;
while(i<str.length()) {
int j=0;
while(j<cs.length()) {
if(NEED TO CHECK IF THERE IS AN INDEX OUT OF BOUNDS EXCEPTION) {
result = false;
break;
}
if(str.charAt(i+j)==cs.charAt(j)) {
result|=true; //result = false or true ->>>>> which is true.
j++;
} else {
result = false;
break;
}
}
i++;
}
return false;
}
Let's say:
String str = "llpll"
Charsequence cs = "llo"
I want to make sure this method works properly in the above case where the Charsequence has one or more char to check but the String runs out length. How should I write the first if statement?
if (i+cs.length() > str.length()){
OUT OF BOUNDS
}
Well if it were me first thing I'd check is that the length of my char sequence was <= to the length of my string.
As soon as you chop that logic path out.
If the lengths are equal you can just use ==
Then it would occur that if you chopped up str
into cs length parts, you could do a straight comparison there as well.
e.g str of TonyJ and search for a three character sequence would pile through
Ton
ony
nyJ
One loop, one if statement and a heck of a lot clearer.
I would suggest using this and using the contains method therein.
Edit - For the reading impaired:
The linked method is not from java.lang.String or java.lang.Object
If you'd bother to actually look at the links, you would see that it is the Apache Commons-Lang API and the StringUtils.contains(...) method that I reference, which very clearly answers the question.
If this is for your homework, which I suspect it is, then I suggest you take a look at the API for the String class to see what other methods are available to help find the location of one String within another.
Also consider looking at the source code for String to see how it implements it.
I'm sure you already know this, but it is in fact possible to see the actual source code of the built-in classes and methods. So I'd take a look there for a start. The String class is especially interesting, IMO.
I am struggling with the charAt method.what i want to know is if when you use charAt, are you able to use more than one number in the parameter, so that you look at more than one character in one method?
No, there is no vanilla JavaScript method for that. You could always write one that prototypes the String object, though:
String.prototype.charsAt = function(indexes) {
var returned = [ ];
for(var i = 0; i < indexes.length; i++)
{
returned.push(this.charAt(indexes[i]));
}
return returned;
}
You can then call it using:
var text = 'mystring';
alert(text.charsAt([0, 1]));
You can see a working demo here > http://jsfiddle.net/MDNRS/. As others have said though, this is really entirely trivial, as you should use substr() or other methods.
From javadoc:
charAt
public char charAt(int index)
Returns the char value at the specified index. An index ranges from 0 to length() -
The first char value of the sequence is at
index 0, the next at index 1, and so on, as for array indexing.
If you need something else you can use toCharArray() to access the underlying char[] and do what you need
looks like your understanding of method charat(int index) is a little bit off. Calling this method is simply to get a single character at specified index.
If you are looking for searching a specific character sequence, you might want to look into the contains(CharSequence cs) method of String class.
Reference:
Java API
I wrote this little function just for practice, but an exception ("String index out of range: 29") is thrown and I don't know why...
(I know this isn't the best way to write this function and can I use regular expressions.)
This is the code:
public String retString(String x)
{
int j=0;
int i=0;
StringBuffer y = new StringBuffer(x);
try
{
while ( y.charAt(i) != '\0' )
{
if (y.charAt(i) != ' ')
{
y.setCharAt(j, y.charAt(i));
i++;
j++;
}
else
{
y.setCharAt(j, y.charAt(i));
i++;
j++;
while (y.charAt(i) == ' ')
i++;
}
}
y.setCharAt(j,'\0');
}
finally
{
System.out.println("lalalalololo " );
}
return y.toString();
}
Are you translating this code from another language? You are looping through the string until you reach a null character ("\0"), but Java doesn't conventionally use these in strings. In C, this would work, but in your case you should try
i < y.length()
instead of
y.charAt(i) != '\0'
Additionally, the
y.setCharAt(j,'\0')
at the end of your code will not resize the string, if that is what you are expecting. You should instead try
y.setLength(j)
This exception is an IndexOutOfBoundsException but more particularly, a StringIndexOutOfBoundsException (which is derived from IndexOutOfBoundsException). The reason for receiving an error such as this is because you are exceeding the bounds of an indexable collection. This is something C/C++ does not do (you check bounds of collections manually) whereas Java has these built into their collections to avoid issues such as this. In this case, you're using the String object like an array (probably what it is in implementation) and going over the boundary of the String.
Java does not expose the null terminator in the public interface of String. In other words, you cannot determine the end of the String by searching for the null terminator. Rather, the ideal way to do this is by ensuring you do not exceed the length of the string.
Java strings are not null-terminated. Use String.length() to determine where to stop.
Looks like you are a C/C++ programmer coming to java ;)
Once you have gone out of range with .charAt (), it doesn't reach null, it reaches a StringIndexOutOfBoundsException. So in this case, you will need a for loop that goes from 0 to y.length()-1.
a much better implementation (with regex) is simply return y.replaceAll("\\s+"," "); (this even replaces other whitespace)
and StringBuffer.length() is constant time (no slow null termination semantics in java)
and similarly x.charAt(x.length()); will also throw a StringIndexOutOfBoundsException (and not return \0 like you'd expect in C)
for the fixed code:
while ( y.length()>i)//use length from the buffer
{
if (y.charAt(i) != ' ')
{
y.setCharAt(j, y.charAt(i));
i++;
j++;
}
else
{
y.setCharAt(j, y.charAt(i));
i++;
j++;
while (y.charAt(i) == ' ')
i++;
}
}
y.setLength(j);//using setLength to actually set the length
btw a StringBuilder is a faster implementation (no unnecessary synchronization)
In php, the method ucwords converts any string in a string where each words first character is in uppercase, and all other characters are lower case.
I always end up making my own implementation, and I'm wondering if a standard method exists.
That's called capitalization. Use Apache Commons's StringUtils to do that.
See more here:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html
WordUtils is also worth looking at. See here
Otherwise it's a rather simple fix such as; String string1 = someString.substring(0,1).toUpperCase() + someString.substring(1);
You can put it in a function, and call it whenever you need. Saves you the trouble of maintaining libraries you don't need. (not that apache commons is ever trouble, but you get the point..)
EDIT: someString.substring(1) part can be written as someString.substring(1).toLowerCase() just to make sure that the rest of the string is in lowercase
I don't know about any direct equivalent, but you can always write one:
public static String capitalize(String input) {
if (input == null || input.length() <= 0) {
return input;
}
char[] chars = new char[1];
input.getChars(0, 1, chars, 0);
if (Character.isUpperCase(chars[0])) {
return input;
} else {
StringBuilder buffer = new StringBuilder(input.length());
buffer.append(Character.toUpperCase(chars[0]));
buffer.append(input.toCharArray(), 1, input.length()-1);
return buffer.toString();
}
}