i'm new to java, start a project 7 days ago, today with some folks from this place i successed to pass through one problem, but still there's one more...
in last problem i needed to search an string and highlight it, but now, my problem is:
Why selection index are not same to the indexes i search for after some unknown character which i dont know my self :|
this is my button code:
int startFrom = jEditorPane1.getSelectionStart();
if(jEditorPane1.getSelectionStart() == jEditorPane1.getSelectionEnd()){
startFrom = -1;
}
String searchWord = jTextField3.getText();
int searchIndex = jEditorPane1.getText().indexOf(searchWord, startFrom + 1);
if(searchIndex != -1){
jEditorPane1.requestFocusInWindow();
jEditorPane1.select(searchIndex, searchIndex+searchWord.length());
}
else{
jEditorPane1.setSelectionStart(0);
jEditorPane1.setSelectionEnd(0);
}
and i'm sure that i need to do some string processing, to convert string index to swing jEditorPane/JTextPane index
for example:
i search for do in string like this:
"Hey,
How do you do?"
and it highlight it this way:
"Hey,
How doyou do?"
which mean it started one index forther that what it should, and in here it's casue escape char of \n and i dont know, cause some time it happen in single row text...
how can i get ride of this?
See Text and New Lines for more information and a solution. The basics of this link is to use:
int length = textPane.getDocument().getLength();
String text = textPane.getDocument().getText(0, length);
The above will only return "\n" as the EOL string so the offsets will match when you do a search and then select the text.
Related
I've got some String, and I'd like to replace some chars in it. Everything was running fine until the String hasn't two or more same chars, the program just replacing the first one, and I'm not able to change the second one.
StringBuilder userTitleBuilder = new StringBuilder(conversedTitle);
while (score>1) {
userLetter = userInput.next().charAt(0);
if (movieTitle.contains(String.valueOf(userLetter))) {
charIndex = movieTitle.indexOf(userLetter);
userTitleBuilder.replace(charIndex,userTitleBuilder.length(), String.valueOf(userLetter));
System.out.println(userTitleBuilder);
} else {
--score;
System.out.println("Wrong\nTries left "+score);
}
}
Here's the explanation of this code:
User from the start the program has a score equals to 10. userLetter it's just a char that will get some letter from the user, then if statement checking if movieTitle variable has char equals to that user just entered, if yes, charIndex will have it position (but it contains only first index, what if in word are more same letters?) now userTitleBuilder replace the chars in string that has that many "_" that movieTitle lenght, it's just covering the title.
*movieTitle and userTitleBuilder has the same value = "CocaCola"
I'd like to not get ready solution. I'd like to have some kind of hint, how do I replace more than one same character in String
A method called String.replace("old","new") can be used.
Follow this doc.
I’m developing an android app that gets objects from a server and shows them in a simple list.
I’m trying to figure out how to deal with long object’s titles :
Every title populates a designated multi-line TextView.
If a title is longer than 16 characters, it messes with my desired UI.
There are two scenarios I need to solve -
1). If the title is longer than 16 characters & contains more than one word, I need to split the words into different lines (I tried to .split("") and .trim(), but I don’t want to use another view, just break a line in the same one, and the use in ("") seems unreliable to me).
2). If the title is longer than 16 characters and contains only one long word, I only need to change font size specifically.
Any ideas for a good and reliable solution?
Thanks a lot in advance.
use SpannableString for a single view
For title:
SpannableString titleSpan = new SpannableString("title String");
titleSpan.setSpan(new RelativeSizeSpan(1.3f), 0, titleSpan.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
for Message
SpannableString messageSpan = new SpannableString("Message String");
messageSpan.setSpan(new RelativeSizeSpan(1.0f), 0, messageSpan.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
set in TextView
tvTermsPolicyHeading.setText(TextUtils.concat(titleSpan, messageSpan));
Code like below it will work as you need
String title; //your title
//find length of your title
int length = title.length();
if (length>16){
string[] titles = myString.split("\\s+");
int size = titles.length;
if (size < 2){
yourTextview.setText(title);
// reduce the text size of your textview
}else {
String newTitle= "";
for (int i=0;i<titles.length;i++){
newTitle = titles[i]+"\n"
}
yourTextview.setText(newTitle);
}
}
You can split and then concatenate the words using "\n" if there are more than one words.
In case of long word
You can see this question here
Auto-fit TextView for Android
try this:
if(title.split(" ").size > 1){
String line1 = title.substring(0, 16);
int end = line1.lastIndexOf(" ");
titleTextView.setText(title.substring(0,end) + "\n" +
title.substring(end+1,title.size-1);
}else{
titleTextView.setText(title);
titleTextView.setTextSize(yourTextSize);
}
this code should work perfectly for your case.
first of all I want to say that I am kinda new to Java. So please be easy on me :)
I made this code, but I cannot find a way to change a character at a certain substring in my progress bar. What I want to do is this:
My progressbar is made out of 62 characters (including |). I want the 50th character to be changed into the letter B (uppercase).It should look something like this: |#########----B--|
I tried several things, but I dont know where to put the line of code to make this work. I tried using the substring and the replace code, but I can't find a way to make this work. Maybe I need to write my code in a different way to make this work? I hope someone can help me.
Thanks in advance!
int ecttotal = ectcourse1+ectcourse2+ectcourse3+ectcourse4+ectcourse5+ectcourse6+ectcourse7;
int ectmax = 60;
int ectavg = ectmax - ecttotal;
//Progressbar
int MAX_ROWS = 1;
for (int row = 1; row == MAX_ROWS; row++)
{
System.out.print("|");
for (int hash = 1; hash <= ecttotal; hash++)
System.out.print ("#");
for (int hyphen = 1; hyphen <= ectavg; hyphen++)
System.out.print ("-");
System.out.print("|");
}
System.out.println("");
System.out.println("");
}
Can you tell a little more what you want. Because what i sea it that, that you write some string into console. And is not way to change that what you already print to console.
Substring you can use only at String varibles.
If you want to change lettir with substring method in string varible try smth. like this:
String a="thi is long string try it";
if(a.length()>50){
a=a.substring(0,49)+"B"+a.substring(51);
}
Other way to change charater in string is to use string builder like this:
StringBuilder a= new StringBuilder("thi is long string try it");
a.setCharAt(50, 'B');
Sure you must first check the length of string to avoid the exceptions.
I hope that I helped you :)
Java StringBuilder has method setCharAt which can replace character at position with new character.
StringBuilder myName = new StringBuilder(<original string>);
myName.setCharAt(<position>, <character to replace>);
<position> starts with index 0
In your case:
StringBuilder myName = new StringBuilder("big longgggg string");
myName.setCharAt(50, 'B');
You can replace a certain index in a string by concatenating a new string around the intended index. For example the following code replaces the letter c with the letter X. Where 2 is the intended index to replace.
In other words, this code replaces the 3rd character in the string.
String s = "abcde";
s = s.substring(0, 2) + "X" + s.substring(3);
System.out.println(s);
I have a question regarding indexOf(). I am trying to program an EmailExtractor (Yes, this is a homework but I am not looking for code) which extracts the entire email address from a sentence that is input by a user.
For example -
User Input: Mail us at abc#def.ghi.jk with your queries.
The program will then display abc#def.ghi.jk from the above String. I understand indexOf() and substring() are required.
The idea I have now is to use indexOf() to locate the '#', and then search for the empty space just before the email address input by the user (nth).
My code is as follows:
System.out.println("This is an Email Address Extractor.\n");
System.out.print("Enter a line of text with email address: ");
String emailInput = scn.nextLine();
int spaceAt = emailInput.indexOf(" ");
for (int i = 1; i <= emailInput.indexOf("#"); i++){
if (spaceAt < emailInput.indexOf("#")) {
spaceAt = emailInput.indexOf(" ", spaceAt + 1);
}
}
I understand and am aware of the problem in my code.
1) "Mail us at abc#def.ghi.jk with your queries".indexOf(" ") is 4, I am trying to get 10. However, the IF Condition I have input will cause it to skip to the next instance of indexOf() which is 25. (Because 10 < 14).
How do I go about avoiding this from happening?
Once again, I am not looking for purely the answer rather, I am trying to work around a solution. Thanks in advance!
How about finding the space before and after the #
int at = emailInput.indexOf('#');
int start = emailInput.lastIndexOf(' ', at) + 1;
int end = emailInput.indexOf(' ', at);
if (end == -1) end = emailInput.length();
String email = emailInput.substring(start, end);
you can use regular expressions instead of using indexOf() and substring()
^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"+"[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"
use the Pattern and Matcher to validate the email id in your string.
This may give you a clear view on it
One thing that you could do is call indexOf and test the result in the same iteration of the loop, instead of saving the check for the next iteration. Something like this in mostly pseudocode:
spaceAt := 0
indexOfAtSign := emailInput.indexOf('#');
while (spaceAt < indexOfAtSign) { // you never really used i anyway
temp := index of next space
if (temp > indexOfAtSign) break;
else spaceAt = temp;
}
(There'd need to be a small bit of corner-case testing, but only for if there are no spaces either before the # sign or after the # sign)
I'm moving some code from objective-c to java. The project is an XML/HTML Parser. In objective c I pretty much only use the scanUpToString("mystring"); method.
I looked at the Java Scanner class, but it breaks everything into tokens. I don't want that. I just want to be able to scan up to occurrences of substrings and keep track of the scanners current location in the overall string.
Any help would be great thanks!
EDIT
to be more specific. I don't want Scanner to tokenize.
String test = "<title balh> blah <title> blah>";
Scanner feedScanner = new Scanner(test);
String title = "<title";
String a = feedScanner.next(title);
String b = feedScanner.next(title);
In the above code I'd like feedScanner.next(title); to scan up to the end of the next occurrence of "<title"
What actually happens is the first time feeScanner.next is called it works since the default delimiter is whitespace, however, the second time it is called it fails (for my purposes).
You can achieve this with String class (Java.lang.String).
First get the first index of your substring.
int first_occurence= string.indexOf(substring);
Then iterate over entire string and get the next value of substrings
int next_index=indexOf( str,fromIndex);
If you want to save the values, add them to the wrapper class and the add to a arraylist object.
This really is easier by just using String's methodsdirectly:
String test = "<title balh> blah <title> blah>";
String target = "<title";
int index = 0;
index = test.indexOf( target, index ) + target.length();
// Index is now 6 (the space b/w "<title" and "blah"
index = test.indexOf( target, index ) + target.length();
// Index is now at the ">" in "<title> blah"
Depending on what you want to actually do besides walk through the string, different approaches might be better/worse. E.g. if you want to get the blah> blah string between the <title's, a Scanner is convenient:
String test = "<title balh> blah <title> blah>";
Scanner scan = new Scanner(test);
scan.useDelimiter("<title");
String stuff = scan.next(); // gets " blah> blah ";
Maybe String.split is something for you?
s = "The almighty String is mystring is your String is our mystring-object - isn't it?";
parts = s.split ("mystring");
Result:
Array("The almighty String is ", " is your String is our ", -object - isn't it?)
You know that in between your "mystring" must be. I'm not sure for start and end, so maybe you need some s.startsWith ("mystring") / s.endsWith.