Reputation: 468
I need to format this String
:
"public class geo {
public static void main(String[] args) {
if (true) {
System.out.print("Yes");
if (false) {
System.out.prinln("DSadaDSa");
x = 4;
blahblah();
}
}
}
}"
to get everything between:
"public class geo {
public static void main(String[] args) {
}
}"
So in this example the String I want to get is:
"if (true) {
System.out.print("Yes");
if (false) {
System.out.prinln("DSadaDSa");
x = 4;
blahblah();
}
}"
Currently I am doing it a bit of a messy way by replacing the char sequences I don't want with empty Strings, but the String
I am left with at the end
"if (true) {
System.out.print("Yes");
if (false) {
System.out.prinln("DSadaDSa");
x = 4;
blahblah();
}
}"
still has the leading tabs on each line.
Is there an easy way to remove these tabs so the String
is effectively shifted over to the left by one tabs width?
Upvotes: 0
Views: 3450
Reputation: 1105
Are you familiar with the String class's trim()
method?
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#trim()
From the docs:
... Returns a copy of the string, with leading and trailing whitespace omitted ...
I believe this will work well for your situation. You can build on what Jakob wrote, but instead of doing lines[i]=lines[i].substring(/*...*/);
simply do lines[i] = lines[i].trim();
Upvotes: 2
Reputation: 7920
Try this:
String s=what you already have;
//split the string into lines
String[] lines=s.split("\n");
//cut off the beginning of each one
for(int i=0;i<lines.length;i++)
lines[i]=lines[i].substring(/*1, 2, 4, or 8 depending on tab formatting*/);
return s;
Upvotes: 1