theta
asked on
Is there a equivalent of strncpy() in Java?
I have to remove carraige return from the end of the String, is there a method to do that?
Thanks.
Theta.
Thanks.
Theta.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I was typing my comment when imladris posted so I didn't see his answer. Keep in mind that the carriage return and newline pair are usually seen in that order. As a result the posted answer will remove the last character from the String which is most likely going to be newline, not carriage return.
Playing around a little more, the simplest solution with the least side effects is likely to be String.replace():
String s = <your string>
s = s.replace('\r', '');
This will return a new String with all carriage returns removed.
Jim
Playing around a little more, the simplest solution with the least side effects is likely to be String.replace():
String s = <your string>
s = s.replace('\r', '');
This will return a new String with all carriage returns removed.
Jim
ASKER
Imladris solution worked fine.
Jim, thankyou for such detailed description on strings. I tried your solutions and they worked too.
Theta.
Jim, thankyou for such detailed description on strings. I tried your solutions and they worked too.
Theta.
String s = <your string>
s = s.trim();
If you want to just remove carriage return, you might consider something like:
String s = <your string>
int crIndex = s.indexOf("\r");
s = s.substring(0, crIndex);
This will take a substring of the original String that contains everything from the beginning of the String up to but not including the index of the first carriage return character. Of course, everything after the carriage return is discarded as well.
If you really want to remove just carriage returns and leave everything else intact, you might consider this:
String s = <your string>
StringBuffer buf = new StringBuffer(s);
for (int index = buf.length() - 1; index >= 0; --index) {
if (buf.charAt(index) == '\r') {
buf.deleteCharAt(index);
}
}
s = buf.toString();
If you want to remove just the last occurrence of carriage return, break the loop after deleteCharAt().
There is also a rather inefficient way of doing it with StringTokenizer but I doubt that it would be necessary to go to that length.
Best regards,
Jim Cakalic