currently I am developing a basic AI that responds to user input.
I have this line of code:
if (value.contains("hi")){
test.setText("Hello.");
speakOut();}
}
But this line is very easily triggered with words that are not "hi", such as this, which also contains "hi".
What code can I use to search for exact words rather than certain characters?
Then use the equals method :
"hi".equals(value)
If you have a sentence with the word hi, you could just split it :
String s = "Hi I'm this";
String [] words = s.split("\\s+"); //split by whitespaces
loop: for(String word : words){
if("hi".equals(word.toLowerCase())){
System.out.println("hello");
break loop;
}
}
Like the comments stated, you may have a sentence like "Hi, blablabla" and this won't work. But now that you have the idea you will be able to find a good regex that will catch only words.
Related
How can I find how many characters are there in each word of a TextView in Android. I want to set few words of my TexView to bold type. So for instance if the text view has a text "Happy Coding, Fellow Coders". I would like to set "Coding" & "Coders" to bold type.
Try this solution. It contains counting words based on the comma, colon or semicolon and dot characters :
String str = "Happy Coding, Fellow Coders";
String[] strArr = str.split(",| |.");
Log.e("TAG", "split String: " + strArr);
If you want to split only from whitespaces, then use :
.split("\\s+") instead of .split(" ")
Then you can simply use the loops to count the characters of every words.
I have a sentence,
hello, What you are doing?How are you?
I wanted to split the sentence with characters such as .,?
I have achieved it using split function
and the output is:
arr[0]=hello
arr[1]=What you are doing
arr[2]=How are you
but I want the array as
arr[0]=hello
arr[1]=,
arr[2]=What you are doing
arr[3]=?
arr[4]=How are you
arr[5]=?
I have done this code
String text = "hello, What you are doing?How are you?";
String[] arr= text.split("[\\.,!;?:\"]+");
for (String str : arr) {
System.out.println(str);
}
Please help.
The general strategy to preserve text while also splitting on it at the same time is to use lookarounds. Lookarounds assert logic, but do not actually consume any text. They are basically zero width. I split below using the pattern:
(?=[\\.,!;?:\"])|(?<=[\\.,!;?:\"])
This says to split if we lookahead or lookbehind and see a punctuation character.
String sentence = "hello, What you are doing?How are you?";
String[] parts = sentence.split("(?=[\\.,!;?:\"])|(?<=[\\.,!;?:\"])");
for (String part : parts) {
System.out.println(part);
}
hello
,
What you are doing
?
How are you
?
Demo
You might also want to run String#trim on each term to get the exact output you want.
First of all, I have gone through questions similar to the problem I am facing and those solutions are not working for me.
I have a TextView field on my Android app which is supposed to display multiple paragraphs i.e multiple new lines. I am getting this string from a database present in my online server as a JSON.
The text contains \n in it and I am expecting it to create new lines once it is received by the app. But it displays the whole text without any breaks along with "\n" character.
Below is the text present in my database.
First line. \nSecond line. \nThird line.
JSON string received by me inside the app.
{
"server_response": [{
"news_expand": "First line. \\nSecond line. \\nThird line."
}]
}
Code to extract string from JSON. I have left out the code to get get JSONArray and JSONObject for simplicity.
na_expand = gna_jo.getString("news_expand");
String extracted from the JSON. Got this by printing the na_expand string.
First line. \nSecond line. \nThird line.
Code to display the text in the TextView. Note the below 'na_expand' is an SparseArray present in a different activity hence the 'get(position)' code.
art_expand.setText(na_expand.get(position));
Below is the text I get on the emulator.
First line. \nSecond line. \nThird line.
What am I doing wrong here?
I think you should replace \n with \n in your string before setting test to your textview same below
b= b.replaceAll("\\n","\n");
So I found a workaround to the problem. As I was not sure where the issue was happening with \n, I modified my text present in the database to have a symbol other than \n. For eg: ~
First line.~Second line.~Third line.
You can use a website like this - https://www.gillmeister-software.com/online-tools/text/remove-line-breaks.aspx to replace the line breaks with any symbol you want.
Next, I used the StringSplitter class to break the string received in JSON and then again join it together with \n.
String joined;
String expand_temp = na_expand.get(position);
TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter('~');
splitter.setString(expand_temp);
StringBuilder stringBuilder = new StringBuilder();
for (String s_temp : splitter) {
stringBuilder.append(s_temp + "\n");
}
joined = stringBuilder.toString().trim();
This worked! I used this string in setText.
art_expand.setText(joined);
Try below code
myTextView.setText(Html.fromHtml("yourString with additional html tags"));
It will resolve all the html tags accordingly and effects of the tags will be reflected as well.
NOte: For devices greater than Nougat use below code
myTextView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>", Html.FROM_HTML_MODE_COMPACT));
Hope that helps
The \ character is an escape character in JSON. So, when you get \\n, it actually means \n, not the newline character, which should have been just \n. So what you see is an expected behaviour. The JSON you get should have ideally been:
{
"server_response": [{
"news_expand": "First line. \nSecond line. \nThird line."
}]
}
Get your server to respond properly, otherwise you'll have to strip the unnecessary \.
Do you haveandroid:singleLine="true" on your TextView? If yes it will ignore the \n and will place the text in a single line.
You can just add replaceAll("\\n","\n") when you set value to your art_expand EditText. It should be:
art_expand.setText(na_expand.get(position).replaceAll("\\n","\n"));
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));
TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter('\n');
splitter.setString(tweetMessage);
tweetMessage = "";
for (String s : splitter)
{
Log.v(getClass().getSimpleName(), "Spliter :: "+ s);
tweetMessage +=s;
}
But this shows up the newline characters as Squares how do I get Rid of that
The characters you're seeing as squares probably aren't '\n' ('\u000A') characters.
If you're seeing a multiple lines in your output then it's possible that multiple characters are being used to split the lines. It might be '\r\n' but it could be something else.
Your best bet is to use a debugger to check exactly what the String contains before you split it. Or you could add some debug code like so:
for (int u : tweetMessage.toCharArray()) {
Log.v(getClass().getSimpleName(), String.format("\\u%04X",u));
}
If you see \u000D \u000A then your lines are separated by "\r\n". This means you can't use a SimpleStringSplitter to split the string since that will only split on a single character.
If you don't want to parse the string manually, you could use the String.split() method:
for (String s : tweetMessage.split("\r\n") {
//do something with s
}
If you need to remove newline/tab characters at the beginning and the end of a string (not the ones in the middle of the string) just use .trim() function to do the tric. This will remove white spaces from the begging and the end of the string.
Ex:
String xmlVersionDate = rootNode.getChildNodeWithName("last-updated").getValue().trim();