java strings manipulation

if we are using StringTokenizer to perform task on a string, and apart from reading and writing we also have to change few words in that string. In this case do we have to make a StringBuffer object or will the StringTokenizer object will do good for making changes to the string ?

String is an immutable (non-changeable) sequence of characters in Java. StringBuffer is just like String, but it is mutable. So, for making changes, StringBuffer will be good. StringTokenizer is used to tokenize (split into different recognizable pieces) an input string.

@tijoforyou : yes of course, but when i’ve tokenized the string, can changes be made to them successfully or still we have to make a StringBuffer object for StringTokenizer object to suppose change a word in that string ?

Once you tokenize, you can rebuild the string (or make a new one) using the separated tokens (each token is again a string). So, make the changes, and you can build/rebuild a string.

You can do something like

String src;
StringTokenizer st = new StringTokenizer(src);
String newString = "";
while (st.hasMoreTokens()) {
    String currentToken = st.nextToken();
    if (some_change_is_to_be_made == true)
        currentToken = makeChanges(currentToken);
    newString = newString + currentToken + "";
newString = newString.trim();

to build the new string.

alright got that now.

one more doubt, if in a question 5<= N <=5000 is a constrain, then not giving conditional statement for N will get the question wrong ?

No. If the constraint is given in the question, then ALL test cases respect that constraint. YOu need not add additional checks. There is nothing wrong in doing that as well. :slight_smile:

i completed 4 AUG Challenge problems and tested them with various inputs, still all gave WA here. you also must have gone through same sometime or the other. cam you give something that can help, cause i’m annoyed of getting right on computer and wrong on CC.

Hi, there might be some silly corner cases, that we might have failed to look at, and which is causing us wrong answers and runtime errors. They are, usually, very small test cases, or very large test cases, and sometimes, they can be special values that can come in the input. Usually, we need to handle them separately to get the answers right.

Even if you are unable to solve a particular problem, do not worry. At least you tried. Wait for the editorials, which will be out after the contest is over. There, detailed explanations are given, and sample programs are also given. Sometimes, active discussions also take place on that page. Read and understand them, to find where the mistake was. In the next contest, you can try and will surely improve!


means somewhere i’m missing the special cases. will lay special emphasis on these form now on. thanks for help. :slight_smile:

src is the original string.

Sure. And, best wishes! :smiley: