I have a very weird problem. After writing this:
for (File f : currentFile.listFiles()) {
if (f.isDirectory()){
System.out.println(f.getName()+"\t"+"Dir\t"+Command.getpremission(f)+"\t"+f.getTotalSpace());
}
else{
System.out.println(f.getName()+"\t"+"File\t"+Command.getpremission(f)+"\t"+f.getTotalSpace());
}
I see this printed:
see.txt File rw 267642728448
see1.txt File rw 267642728456
see2.txt File rw 267642728448
Why is there a problem with the tabs?
Building on this question, I use the following code to indent my messages:
String prefix1 = "short text:";
String prefix2 = "looooooooooooooong text:";
String msg = "indented";
/*
* The second string begins after 40 characters. The dash means that the
* first string is left-justified.
*/
String format = "%-40s%s%n";
System.out.printf(format, prefix1, msg);
System.out.printf(format, prefix2, msg);
This is the output:
short text: indented
looooooooooooooong text: indented
This is documented in section "Flag characters" in man 3 printf.
The "problem" with the tabs is that they indent the text to fixed tab positions, typically multiples of 4 or 8 characters (depending on the console or editor displaying them). Your first filename is 7 chars, so the next tab stop after its end is at position 8. Your subsequent filenames however are 8 chars long, so the next tab stop is at position 12.
If you want to ensure that columns get nicely indented at the same position, you need to take into account the actual length of previous columns, and either modify the number of following tabs, or pad with the required number of spaces instead. The latter can be achieved using e.g. System.out.printf with an appropriate format specification (e.g. "%1$13s" specifies a minimum width of 13 characters for displaying the first argument as a string).
The length of the text that you are providing in each line is different, this is the problem, so if the second word is too long (see2.txt is long 8 char which corresponds to a single tab lenght) it prints out a tab which goes to the next tabulation point.
One way to solve it is to programmatically add a pad to the f.getName() text so each text generated: see.txt or see2.txt has the same lenght (for example see.txt_ and see2.txt) so each tab automatically goes to the same tabulation point.
If you are developing with JDK 1.5 you can solve this using java.util.Formatter:
String format = "%-20s %5d\n";
System.out.format(format, "test", 1);
System.out.format(format, "test2", 20);
System.out.format(format, "test3", 5000);
this example will give you this print:
test 1
test2 20
test3 5000
In continuation of the comments by Péter and duncan, I normally use a quick padding method, something like -
public String rpad(String inStr, int finalLength)
{
return (inStr + " " // typically a sufficient length spaces string.
).substring(0, finalLength);
}
similarly you can have a lpad() as well
As mentioned by other folks, the variable length of the string is the issue.
Rather than reinventing the wheel, Apache Commons has a nice, clean solution for this in StringUtils.
StringUtils.rightPad("String to extend",100); //100 is the length you want to pad out to.
The problem is the length of the filenames. The first filename is only 7 chars long, so the tab occurs at char 8 (doing a tab after every 4 characters). However the next filenames are 8 chars long, so the next tab won't be until char 12. And if you had filenames longer than 11 chars, you'd run into the same problem again.
You can use this example to handle your problem:
System.out.printf( "%-15s %15s %n", "name", "lastname");
System.out.printf( "%-15s %15s %n", "Bill", "Smith");
You can play with the "%" until you find the right alignment to satisfy your needs
You can also pad a string to the required length using Guava's Strings.padEnd(String input, int minLength, char padding)
Related
I found a dictionary sample in GitHub that I am currently experimenting with. The sample database used hyphen between the searched word and the word's meaning. So something like this.
abbey - n. a monastery ruled by an abbot
I looked into the dictionary database java file and found the following code:
String[] strings = TextUtils.split(line, "-");
I have my own database that translates Korean words to English. However I didn't use hyphen while creating it. So is there a way to not use hyphen or any other symbols but simply spaces? Also this is part of an android app.
Edit- An example of my own dictionary would be something like
abbey a monastery ruled by an abbot
Edit-
The problem here is that the old code only differentiates and recognizes the words and the meaning only if they are separated by hyphen. How do I make this so it works with spaces alone.
To remove a character in a String use String.replace
String newString = line.replace("-","");
To replace with a space simply use
String newString = line.replace("-"," ");
String mystring = mystring 1.replace("_"," "); if you want space give space.
As I understand it, you want to split your String to get the output like
abbey - n. a monastery ruled by an abbot
[abbey][n. a monastery ruled by an abbot]
You can use String.split(String, int) to force the number of split.
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times
Let's use it like :
String[] array = s.split(" ", 2);
This will split your String on the regex " " but will limit the size of the output to 2 cells. So it will only split once, put the left part on the first cell and the right part on the second cell.
Without this limit argument, the method would keep split the right part again using a bigger array.
Note: this will be a problem if your word is a sentence in the left part.
This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 8 years ago.
Hi how can i return Grapes from the string below, i want to search through a string and return a text in the middle of the string after four character and discard the rest of the text.
String grapes = "2 x Grapes #Walmart";
Thanks for helping me guys the code below worked
String grapes = "2 x Grapes #Walmart";
String[] split = grapes.split("\\s+");
String fsplit = split[2];
my suggestion will be not to use a regex for this . But just in case you find no other way round, use this :
(\w+\s){3}
you will get the third word in the first backreference. \1 or $1 whichever supports your compiler
demo here : http://regex101.com/r/jB5nN0
This may help you:
^[\\d]+\\sx\\s(.*?)\\s+.*?$
Explanation:
Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Match a single digit 0..9 «[\d]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s»
Match the character “x” literally «x»
Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s»
Match the regular expression below and capture its match into backreference number 1 «(.*?)»
Match any single character that is not a line break character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match any single character that is not a line break character «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Assert position at the end of a line (at the end of the string or before a line break character) «$»
Example 1:
i Have an Apple
Example 2:
I Love U
i would like to copy 10 string only, start index from first character.
Delphi code would be like this :
copy('I Have an Apple',0,10)
copy('I Love U',0,10)
Result become
i Have an
I Love U
Any same function in Android?
no method how long the string, i just want the first 10 character
You're probably after .substring(int start,int end) which applied to your code, would be something like the code below, however when you say you would like to copy "10 string only" you should say 10 characters from said string:
String apple = "i Have an Apple";
String appleCopy = apple.substring(0,10); // "i Have an "
If you want to handle the IndexOutOfBoundsException inline, you could do this, as suggested here, which would take the first n characters if the length is sufficient, or the whole string if its shorter.
String appleCopy = apple.substring(0, Math.min(apple.length(), 10));
I newt o regular expressions and been using tutorials, but the regular express I have works sometimes, but doesn't all the time. I am getting my numbers out of the contact list from my android phone. I am trying to get rid of all spaces, '(', ')', and '-'
For example:
1. (555) 867-5309 -> 5558675309
2. 1555-555-5555 -> 15555555555
3. 555-555-5555 -> 5555555555
This is the line I am using
String formatphone = contactPhone.replaceAll("\\s()-","");
For some numbers it only returns number and sometimes it doesn't change the format.
Is it correct? Do i need to format something because I am taking it out of the phone's contact list?
Put the desired characters in a character class:
String formatphone = contactPhone.replaceAll("[ ()-]","");
Ensure that you put the hyphen - at either end.
Try using this:
String formatphone = contactPhone.replaceAll("^.*[\\s\\(\\)-].*", "");
As a regular expression you're defining a set using []. In that set you include any character you want to be replaced. As ( and ) are special meaning characters, you have to escape them. As the - is a special character used to design ranges, it has to be the last character of your set, so if nothing is behind it, it's not a range, but just that character (you could escape it too, though).
I know that if you do something like
myTextView.setText("This is on first line \n This is on second line");
Then it will display properly like this:
This is on first line
This is on second line
When I store that string in a database and then set it to the view it displays as such:
This is on first line \n This is on second line
Here is the line of code I use to extract the string from the database:
factView.setText(factsCursor.getString(MyDBAdapter.FACT_COLUMN));
I simply populate the database from a text file where each line is a new entry into the table so a line would look like this "This is on first line \n This is on second line" and it is stored as text.
Is there a reason that it isn't displaying the \n characters properly? It must be something to do with the string being in the database. Any suggestions?
I found this question Austyn Mahoney's answer is correct but here's a little help:
private String unescape(String description) {
return description.replaceAll("\\\\n", "\\\n");
}
description being the string coming out of your SQLite DB
As Falmarri said in his comment, your string is being escaped when it is put into the database. You could try and unescape the string by calling String s = unescape(stringFromDatabase) before you place it in your TextView.
As a side note, make sure you are using DatabaseUtils.sqlEscapeString() on any kind of data that is from the user or an unknown changeable source when inserting data into the database. This will protect you from errors and SQL Injection.
Try \\n instead of \n. If it throws an exception than use newline keyword in place of \n....newline is one character, ascii 10; it's often entered in a string literal...and will serve your purpose....:)
"This is on first line"||x'0A'||"This is on second line"
The || concatenates strings and the x'0A' is an unescaped newline.
If you're inserting records you'll have to replace every newline with "||x'0A'||" (If your string is double quoted). This may seem clumsy compared to the other asnswers. However if your lines are in separate columns this also works in a select:
SELECT firstline||x'0A'||secondline FROM wherever;
I found this while having the same problem you are: http://www.mail-archive.com/sqlite-users#sqlite.org/msg43557.html
A text area can be in multi line or single line mode. When it is in single line mode newline characters '\n' will be treated as spaces. When in doubt, to switch multi line mode on you can use the following code:
setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
I had the problem that the same code did not work on honeycomb and on froyo, which seem to have different defaults. I am now also excluding the flag when I want to force a field to be single lined.
From the Android doc:
public static final int TYPE_TEXT_FLAG_MULTI_LINE Added in API level 3
Flag for TYPE_CLASS_TEXT: multiple lines of text can be entered into
the field. If this flag is not set, the text field will be
constrained to a single line. Constant Value: 131072 (0x00020000)
http://developer.android.com/reference/android/text/InputType.html#TYPE_TEXT_FLAG_MULTI_LINE
You have to set the flag before you populate the field.