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
Related
I want to reverse a string. I know there are some other methods to do it but I wanted to do in a different way. There is no error but no output when I run my code. I dont understand why "String.valueOf(word.charAt(i)" doesnt return a value? Am I missing something?
String word = "myword";
for (int i = word.length(); i <= 0; i--) {
System.out.print(String.valueOf(word.charAt(i)));
}
The first value of i is out of index. And I also fixed your code. Check below:
String word = "myword";
for(int i=word.length()-1;i>=0;i--){
System.out.print(String.valueOf(word.charAt(i)));}
Just for providing another slightly different solution:
You can use a StringBuilder to reverse a String using its method reverse().
If you have a String, you can use it to initialize the StringBuilder with it and directly reverse it.
This example additionally uses an enhanced for-loop, which always goes through all of the elements. Using that, you can get rid of checking the length of a String and you won't have to use an int i for iterating.
For your requirements, this is a suitable option because you want to reverse the whole String.
String word = "myword";
for (char c : new StringBuilder(word).reverse().toString().toCharArray()) {
System.out.println(c);
}
Note that you can use the reverse() method for printing the reversed word in one line just doing
System.out.println(new StringBuilder(word).reverse().toString());
Your code has 2 issues.
i should be initialized with word.length()-1. Other wise you will get StringIndexOutOfBoundsException
for loop condition should be >= 0.
Below is the corrected code.
String word = "myword";
for(int i=word.length()-1;i>=0;i--) {
System.out.print(word.charAt(i));
}
I've been told that code such as:
for (int i = 0; i < x.length(); i++) {
// blah
}
is actually O(n^2) because of the repeated calls to x.length(). Instead I should use:
int l = x.length();
for (int i = 0; i < l; i++) {
// blah
}
Is this true? Is string length stored as a private integer attribute of the String class? Or does String.length() really walk the whole string just to determine its length?
No, the length of a java string is O(1) because java's string class stores the length as a field.
The advice you've received is true of C, amongst other languages, but not java. C's strlen walks the char array looking for the end-of-string character. Joel's talked about it on the podcast, but in the context of C.
Contrary to what has been said so far, there is no guarantee that String.length() is a constant time operation in the number of characters contained in the string. Neither the javadocs for the String class nor the Java Language Specification require String.length to be a constant time operation.
However, in Sun's implementation String.length() is a constant time operation. Ultimately, it's hard to imagine why any implementation would have a non-constant time implementation for this method.
String stores the length in a separate variable. Since string is immutable, the length will never change.
It will need to calculate the length only once when it is created, which happens when memory is allocated for it.
Hence its O(1)
In the event you didn't know you could write it this way:
for (int i = 0, l = x.length(); i < l; i++) {
// Blah
}
It's just slightly cleaner since l's scope is smaller.
You should be aware that the length() method returns the number of UTF-16 code points, which is not necessarily the same as the number of characters in all cases.
OK, the chances of that actually affecting you are pretty slim, but there's no harm in knowing it.
I don't know how well the link will translate, but see the source of String#length. In short, #length() has O(1) complexity because it's just returning a field. This is one of the many advantages of immutable strings.
No worries even though we are calling length() as a method on x.length(), Actually length is stored as a field/property in String class and this field/property returned by length() method whenever we call " x.length()".
Check out this image link or below code snippet of length() method defined in String class-
ImageLink
public int length() {
return value.length >> coder();
}
length() method returns the length property which is already stored in String class.
According to this, the length is a field of the String object.
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).
I have a string 4.9.14_05_29_16_21 and I need to get 4.9 only. The numbers vary so I can't simply get the first three elements of this char array. I have to find the right most . and substring it till there.
I'm from Python so I'll show Python approach to this.
def foobar(some_string):
location = some_string.rfind('.')
new_string = some_string[0:location]
return new_string
How would I do this in Java?
Use String#lastIndexOf and String#substring:
int location = someString.lastIndexOf('.');
String newString = someString.substring(0, location);
Also note that I've assumed Java's naming convention (i.e. camelCase). If there can be cases where the input does not include a period, you can check if location is negative and include logic to deal with that case.
You should use the following methods:
String.lastIndexOf(int ch) to get the index
String.substring(int beginindex, int endindex) to
extract the String.
Make sure to put an error check in if the string doesn't contain any ., i.e. lastIndexOf returns -1.
public String getBeforePeriod(String input) {
int index = input.lastIndexOf('.');
return index > -1 ? input.substring(0,index) : input;
}
Use String.indexOf() method to provide one second argument to substring() method.
Here is a link to more info.
http://www.tutorialspoint.com/java/java_string_indexof.htm
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.