Having read the documentation of Java's String class, it doesn't appear to support popping from front(which does make sense since it's basically a char array). Is there an easy way to do something like
String firstLetter = someString.popFront();
which would remove the first character from the string and return it?
A String in Java is immutable, so you can't "remove" characters from it.
You can use substring to get parts of the String.
String firstLetter = someString.substring(0, 1);
someString = someString.substring(1);
You can easily implement this by using java.lang.StringBuilder's charAt() and deleteCharAt() methods. StringBuilder also implements a toString() method.
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html
I don't think there is something like that (even because strings can't be changed - a new one needs to be created), but You can use charAt and subString to implement your own.
An example of charAt:
String aString = "is this your homework Larry?";
char aChar = aString.charAt(0);
Then subString:
String anotherString = aString.substring(1, aString.length());
So you basically want to have the String in a FIFO stack? For that you can use a LinkedList which offers under each a pop() method to pop the first from the stack.
To get all characters of a String in a LinkedList, do so:
String string = "Hello World";
LinkedList<Character> chars = new LinkedList<Character>();
for (int i = 0; i < string.length(); i++) chars.add(string.charAt(i));
Then you can pop it as follows:
char c = chars.pop();
// ...
Update: I didn't see the comment that you'd like to be able to get the remaining characters back as a string. Well, your best bet is to create and implement your own StringStack or so. Here's a kickoff example:
public class StringStack {
private String string;
private int i;
public StringStack(String string) {
this.string = string;
}
public char pop() {
if (i >= string.length()) throw new IllegalStateException("Stack is empty");
return string.charAt(i++);
}
public String toString() {
if (i >= string.length()) throw new IllegalStateException("Stack is empty");
return string.substring(i, string.length());
}
}
You can use it as follows:
String string = "Hello World";
StringStack stack = new StringStack(string);
char c = stack.pop();
String remnant = stack.toString();
// ...
To make it more solid, you can eventually compose a LinkedList.
You should look at a StringReader. The read() method returns a single character.
Related
As a novice Java programmer who barely got started in Java programming, I am totally exhausted in trying to find a solution to this issue. A course that I am currently studying gave homework that asked me to create a Java class that has a sort of “reverse” method that returns a new version of the string
of the current string where the capitalization is reversed (i.e., lowercase to uppercase
and uppercase to lowercase) for the alphabetical characters specified in a given condition. Say if I were to reverse “abc, XYZ; 123.” using reverse("bcdxyz#3210."), it must return "aBC, xyz; 123.". (P.S: the class ignores numbers and special characters and the variable "myString" is where the "abc, XYZ; 123." goes to.). So far, I've only managed to return out "aBC, XYZ; 123." with the code below. Am I missing something here?
public String reverse(String arg) {
// TODO Implement method
String arg_no_sym = arg.replaceAll("[^a-zA-Z0-9]","");
String arg_perfect = arg_no_sym.replaceAll("\\d","");
if (myString != null) {
char[] arrayOfReplaceChars = arg_perfect.toCharArray();
char[] arrayOfmyString = myString.toCharArray();
for (int i = 0; i < arg_perfect.length(); i++) {
myString = myString.replace(String.valueOf((arrayOfReplaceChars[i])), String.valueOf((arrayOfReplaceChars[i])).toUpperCase());
}
return myString;
}
else {
return "";
}
}
How about using the methods isUpperCase() and isLowerCase() to check the case of the letters and then use toUpperCase() and toLowerCase() to change the case of them?
I have to iterate over the elements of a string and in each iteration to perform some checks.
My question is:
What is better to use: String or StringBuilder?
Is there any difference in running time of String.charAt(i) or StringBuilder.charAt(i)?
I do NOT have to modify the string, I just have to iterate over all elements.
The only reason to use a StringBuilder is for modifications (as Strings are immutable). In this case you should be fine with iterating over the String itself.
StringBuilder is useful when you modify a string and String when you dont.
For your case String
Regarding Performance: It will be constant time for both or negligible [1]
Note:
When you modify a string when its defined as string, it creates new string instead of actually modifying it and thats why its better to use StringBuilder
e.g)
string a = "hello";
a = "hai";
a new world string is also created here along with hello already created in string pools
Additional: http://blog.vogella.com/2009/07/19/java-string-performanc/
As others have already said, there is no performance difference between the two. You can convince yourself of this by looking at the source. As you can see below, the two are nigh on identical.
String.charAt()
public char More ...charAt(int index) {
if ((index < 0) || (index >= count)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index + offset];
}
StrringBuilder.charAt()
public char charAt(int index) {
if ((index < 0) || (index >= count))
throw new StringIndexOutOfBoundsException(index);
return value[index];
}
In other words, use whatever you already have. If you have a String, use the String, if you have a StringBuilder, use the StringBuilder. The cost of converting from one object to the other will vastly outweigh any performance difference between these two methods.
String and StringBuilder both are classes in Java.
String is used to create a string constant.
StringBuilder name itself indicates to build the string. It means that we can easily do
modification using this class.
In your case you can simply use String class.
Strings are immutable in Java. This means that after each modification a new String is created with latest modified value.
String str = new String("AVINASH");
char check = 's';
int length=str.length();
for(int i=0; i <length ; i++) {
if (check==str.charAt(i)) {
System.out.println("Matched");
}
}
I am working with a program in which I need to use a method call to return a String from an int array. This is what I have of the method so far (I am required to use a method with this header and parameters)
public String toString()
{
for (int i=0;i<NUM_POCKETS;i++)
{
this.getPocketCount(i);
}
}
I basically need the loop to go through all of my "pockets" (array items) and return the stored values into a String to be returned.
I could be missing something very obvious, but for the life of me I do not understand how this information would be stored and returned to the Driver as a String. I know the loop logic is there, but how do I store each increment of i into a String as the loop progresses?
Thanks in advance for any help!
"I am working with a program in which I need to use a method call to return a String from an int array."
If this isn't a homework problem, you can simply use Arrays.toString(int[] array).
String myString = Arrays.toString(myIntArray);
Otherwise, maybe you can do something like this:
String getStringFromIntArray(int[] array) {
StringBuilder builder = new StringBuilder();
for (int num : array)
builder.append(num)
return builder.toString();
}
Try looking into the StringBuilder class. The specification for Java 6 is here.
http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html
You would need a StringBuilder object and just append the value to the object using the .append() function.
as long as this.getPocketCount(i); gives you the value of the array on position i:
public String toString() {
String returnstring= ""; //init empty string
for (int i = 0; i < NUM_POCKETS; i++) {
returnstring += this.getPocketCount(i)+" "; //append(concat) to string
}
returnstring = returnstring.substring(0, returnstring.length()-1); //remove the last " "
return returnstring; //return string
}
the + sign appends the next string
"Hello"+" "+"World" becomes "Hello World"
Edit:
public String toString() {
String returnstring= ""; //init empty string
for (int i = 0; i < NUM_POCKETS-1; i++) { //-1 to place last later
returnstring += this.getPocketCount(i)+" "; //append to string
}
returnstring += this.getPocketCount(NUM_POCKETS-1) //append the last value
return returnstring; //return string
}
Assuming you specifically want to build your String from within the loop, you could use a StringBuilder. It is more verbose than the one-liner offered by Arrays.toString(), but you asked for it:
e.g.
public String toString() {
StringBuilder sb = new StringBuilder(NUM_POCKETS);
for (int i = 0; i < NUM_POCKETS; i++) {
sb.append(this.getPocketCount(i));
}
return sb.toString();
}
Using a StringBuilder within a loop is faster than performing concatenation of each individual element. See: when to use StringBuilder in java
I have a recursive method that reversed a string (HW assignment, has to be recursive). I did it....but its only returning the value of the string after the first pass. By analyzing the output after each pass i can see it does do its job correctly. heres my code, and the output i get below it:
String s = "Hello, I love you wont you tell me your name?";
int k=0;
public String reverseThisString(String s) {
if(k!=s.length()) {
String first =s.substring(0,k)+s.charAt(s.length()-1);
String end = ""+s.substring(k, s.length()-1);
k++;
s=first+end;
System.out.println(s);
this.reverseThisString(s);
}
return s;
}
output:
?Hello, I love you wont you tell me your name
I think you need to change this:
this.reverseThisString(s);
to this:
return this.reverseThisString(s);
otherwise the result of the method call is simply discarded.
I would also recommed that you change k to be a parameter to the method rather than a member.
Like Mark said, you forgot the return statement.
Also, there is an easier way to reverse a string (which is my current homework too :P )
public String reverse(String s) {
if(s.length() <= 1)
return s;
return reverse(s.substring(1))+s.charAt(0);
}
This question already has answers here:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
(16 answers)
Closed 4 years ago.
I need a Iterator<Character> from a String object. Is there any available function in Java that provides me this or do I have to code my own?
One option is to use Guava:
ImmutableList<Character> chars = Lists.charactersOf(someString);
UnmodifiableListIterator<Character> iter = chars.listIterator();
This produces an immutable list of characters that is backed by the given string (no copying involved).
If you end up doing this yourself, though, I would recommend not exposing the implementation class for the Iterator as a number of other examples do. I'd recommend instead making your own utility class and exposing a static factory method:
public static Iterator<Character> stringIterator(final String string) {
// Ensure the error is found as soon as possible.
if (string == null)
throw new NullPointerException();
return new Iterator<Character>() {
private int index = 0;
public boolean hasNext() {
return index < string.length();
}
public Character next() {
/*
* Throw NoSuchElementException as defined by the Iterator contract,
* not IndexOutOfBoundsException.
*/
if (!hasNext())
throw new NoSuchElementException();
return string.charAt(index++);
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
It doesn't exist, but it's trivial to implement:
class CharacterIterator implements Iterator<Character> {
private final String str;
private int pos = 0;
public CharacterIterator(String str) {
this.str = str;
}
public boolean hasNext() {
return pos < str.length();
}
public Character next() {
return str.charAt(pos++);
}
public void remove() {
throw new UnsupportedOperationException();
}
}
The implementation is probably as efficient as it gets.
for (char c : myString.toCharArray()) {
}
Stealing from somebody else in another answer, this is probably the best direct implementation (if you're not going to use guava).
/**
* #param string
* #return list of characters in the string
*/
public static List<Character> characters(final String string) {
return new AbstractList<Character>() {
#Override
public Character get(int index) {
return string.charAt(index);
}
#Override
public int size() {
return string.length();
}
};
}
CharacterIterator it = new StringCharacterIterator("abcd");
// Iterate over the characters in the forward direction
for (char ch=it.first(); ch != CharacterIterator.DONE; ch=it.next())
// Iterate over the characters in the backward direction
for (char ch=it.last(); ch != CharacterIterator.DONE; ch=it.previous())
Short answer:
No, you have to code it.
Long answer:
List and Set both have a method for obtaining an Iterator (there are a few other collection classes, but probably not what your looking for). The List and Set interfaces are a part of the Collections Framework which only allow for adding/removing/iterating Objects like Character or Integer (not primitives like char or int). There is a feature in Java 1.5 called auto-boxing that will hide this primitive to Object conversion but I don't recommend it and it won't provide what you want in this case.
An alternative would be to wrap the String in a class of your own that
implements Iterator<Character>
but that might be more work than it is worth.
Here is a code snippet for doing what you want:
String s = "";
List<Character> list = new ArrayList<Character>(s.length());
for (int i = 0; i < s.length(); i++) {
// note that Character.valueOf() is preferred to new Character()
// you can omit the Character.valueOf() method
// and Java 1.5+ will auto-box the primitive into an Object
list.add(Character.valueOf(s.charAt(i)));
}
Iterator<Character> iterator = list.iterator();
No direct way. Not difficult to code, though:
public static Iterator<Character> gimmeIterator(final String x) {
Iterator<Character> it = new Iterator<Character>() {
String str = x == null ? "" : x;
int pos = -1; // last read
public boolean hasNext() { return(pos+1 < str.length()); }
public Character next() { pos++; return str.charAt(pos); }
public void remove() {
throw new UnsupportedOperationException("remove unsupported for this iterator");
}
};
return it;
}
This can be done with a little help from Apache Commons Lang (if you don't want to use Guava, and want a true java.util.Iterator.
private static Iterator<Character> iterator(String string) {
return Arrays.asList(ArrayUtils.toObject(string.toCharArray())).iterator();
}
With java 8 or newer you can use the stream facility. With the chars() method you can access an IntStream. The IntStream supports the method iterator() that returns an OfInt iterator. OfInt implements Iterator<Integer>.
String str = "foobar";
OfInt ofit = str.chars().iterator();
Iterator<Integer> it = ofit;
It is not a perfect answer, since you asked for Iterator<Character>.
Btw: With str.codePoints() you can also access a code point IntStream.
Not sure if there is a more direct way but you could do something like;
Arrays.asList(string.toCharArray()).iterator();
Scratch that; Arrays.asList doesn't do what I seem to remember it doing.
Edit 2: Seems like it last worked this way in 1.4
The Iterator iterate over a collection or whatever implements it. String class does nost implement this interface. So there is no direct way.
To iterate over a string you will have to first create a char array from it and then from this char array a Collection.
This feels dirty, but you could use Scanner with empty string delimiter:
Scanner scanner = new java.util.Scanner(myInput).useDelimiter("");
Scanner implements Iterator, so scanner is now an Iterator of length-1 strings, which is close.
To continue with the (very?) dirty, in Java 8 you can then do this to succinctly iterate by chars:
for (String s: (Iterable<String>)() -> scanner) {
char c = s.charAt(0);
System.out.println(c);
}
For details on why () -> scanner works (and why it may be dangerous, though not in this use case), see Explain how this lambda can be assigned to an Iterable.