I am getting value from a Bluetooth device, values separated by : colon. I want to get the first value and add it to the same string:
public String process(String raw) {
if (raw != null) {
String[] str_array = raw.split(":");
String humid1 = str_array[0];
if (humid1 != null) {
return raw.add(humid1);
}
} else {
Log.w(TAG, "provided string was null");
}
}
There is no add() method in String class. One can perform String concatenation in Java using + operator.
String s = "abc:def:ghi";
s = s + s.split(":")[0]; // or s += s.split(":")[0]
System.out.println(s);
The above snippet will print abc:def:ghiabc
Add null checks and index bounds checks as per your requirements.
Please check alternative ways at String Concatenation | StackOverflow
EDIT (As per OP's comment on question)
If you're looking to make changes to the input String object 'raw' and expect it to reflect in caller method, then it's not possible as String is immutable in Java. Correct way to achieve that would be to return the result from your method and assign that to String in caller method.
public void myMethod() {
String s = "abc:def:ghi";
s = process(s);
System.out.println(s);
}
public String process(String raw) {
if (raw != null) {
String[] str_array = raw.split(":");
String humid1 = str_array[0];
if (humid1 != null) {
return humid1;
}
}
return null; \\ or throw exception as per your choice.
}
The above snippet should print abc. More details String Immutability in Java | StackOverflow.
Related
I have a String which contains a long paragraph. This paragraph contains various keywords, like "happy", "sad", "disappointed", "satisfied" etc. After searching for this keywords in the paragraph I am trying to generate an outcome.
public static String fileReader() {
JSONParser parser = new JSONParser();
String paragraph = "";
try {
Object obj = parser.parse(new FileReader("file_Path"));
JSONObject jsonobject = (JSONObject) obj;
paragraph = (String) jsonobject.get("paragraph");
return paragraph;
} catch (Exception e) {
e.printStackTrace();
}
return paragraph;
}
// adding the words of the paragraph into a hashset.
public static String sentiment() {
String input20 = fileReader();
Set<String> items = new HashSet<String>(Arrays.asList(input20.split(" ")));
//Array of Keywords
String arr[] = {"happy", "sad", "disappointed", "satisfied"};
if ((items.contains("happy")) || (items.contains("satisfied")) {
return "Positive";
} else if ((items.contains("sad")) || (items.contains("disappointed"))) {
return "Negative";
} else if ((items.contains("happy")) || (items.contains("satisfied")) && (items.contains("sad")) || (items.contains("disappointed"))) {
return "Mixed";
else {
return "Unknown";
}
}
Now, I want to write an if-else loop so that I can give output based on various conditions.
Conditions:
(1) If contains "Happy", 'Satisfied" or(any 1 on those), positive as output.
(2) if contains "Sad", "disappointed" or(any 1 on those), negative asoutput.
(3) If contains "Sad", "Happy", i.e(mixture of words), mixed as output.
(4) else unknown.
Can someone help me out with this logic? I always get the output as the first condition that I have kept.
You don't use the array of keywords, so I ignore it in the below code.
You want the outcome to be Positive if the paragraph contains the words happy or satisifed and not the words sad or disappointed. Hence you need to change the first if condition.
Similarly for the Negative outcome. You want paragraph to contain sad or disappointed but not contain happy or satisfied.
In short, each condition needs to consider all the keywords and not just some of them.
Consider the below code.
String input20 = "I am very happy about the application performance but I am disappointed how it shuts off sometimes";
Set<String> items = new HashSet<String>(Arrays.asList(input20.split(" ")));
//Array of Keywords (not used)
String arr[] = {"happy", "sad", "disappointed", "satisfied"};
String str;
if ((items.contains("happy") || items.contains("satisfied")) && !(items.contains("sad") || items.contains("disappointed"))) {
str = "Positive";
} else if ((items.contains("sad") || items.contains("disappointed")) && !(items.contains("happy") || items.contains("satisfied"))) {
str = "Negative";
} else if ((items.contains("happy") || items.contains("satisfied")) && (items.contains("sad") || items.contains("disappointed"))) {
str = "Mixed";
}
else {
str = "Unknown";
}
System.out.println("Outcome: " + str);
i want to surround with single-quotes if result is null . result=''
and in different case, if result is not empty, surround with single-quotes. like this. result = 'data'
but i thought, this code has problem.
List<ApprovalPath> approvalPaths = new ApprovalPaths(params);
String noticeUsers = String.format("(%s)",StringUtils.toString(getNoticeUsers(approvalPaths),",","'%s'"));
i think that this format will be changed ('%s') but result (null case) = '' and result (not null) = 'data'
i want only single-quotes in two cases(null case/ not null case)
but i guess 'not null case' has double single-quotes..
public class StringUtils {
public static <T> String toString(List<T> list, String seperator) {
return toString(list,seperator,null);
}
public static <T> String toString(List<T> list, String seperator, String format) {
String result = "";
for(T item : list) {
String itemString = item.toString();
if(format!=null)
itemString = String.format(format, itemString);
result += itemString;
System.out.println("return : " + result);
}
return result;
}
}
how can i revise this problem?
i have to revise only this code.
String noticeUsers = String format("(%s)",StringUtils.toString(getNoticeUsers(approvalPaths),",","'%s'"));
This would give you the expected outcome:
StringUtils.defaultIfEmpty(StringUtils.wrap("string", "'"), "\"");
public static String wrap(String str,
String wrapWith) Wraps a String with another String.
A null input String returns null.
StringUtils.wrap(null, *) = null
StringUtils.wrap("", *) = ""
StringUtils.wrap("ab", null) = "ab"
StringUtils.wrap("ab", "x") = "xabx"
StringUtils.wrap("ab", "\"") = "\"ab\""
StringUtils.wrap("\"ab\"", "\"") = "\"\"ab\"\""
StringUtils.wrap("ab", "'") = "'ab'"
StringUtils.wrap("'abcd'", "'") = "''abcd''"
StringUtils.wrap("\"abcd\"", "'") = "'\"abcd\"'"
StringUtils.wrap("'abcd'", "\"") = "\"'abcd'\""
Parameters: str - the String to be wrapper, may be null wrapWith -
the String that will wrap str Returns: wrapped String, null if null
String input Since:
3.4
StringUtils.wrap
I am trying to parse a string from a website using Jsoup and wrote the following test to verify that the parsing
This is my test:
#Test
public void extractBookData() throws Exception {
String bookLink = ""; //some address
Document doc = Jsoup.connect(bookLink).get().html();
Book book = new Book();
assertEquals("Literatür Yayıncılık", book.getPublisher(doc));
}
This is getPublisher(Element) method:
public String getPublisher(Element element){
String tableRowSelector = "tr:contains(Yayınevi)";
String tableColumnSelector = "td";
String tableRowData = "";
element = element.select(tableRowSelector).last();
if (element != null) {
element = element.select(tableColumnSelector).last();
if (element != null) {
tableRowData = element.text().replaceAll(tableRow.getRowName() + " ?:", "").replaceAll(tableRow.getRowName() + " :?", "").replaceAll(" ?: ?", "").trim();
}
}
return tableRowData;
}
The problem is that the actual and expected strings appears the same even though JUnit tells otherwise.
I am open to your suggestions please.
I have had this same issue before, this is a non-breaking space (char 160) wich is in your text instead of a space (char 32). In my case the text came from an html text input value, yours looks like it hes also come from html.
The solution I used was just too replace all non breaking space chars with a space.
I have to create file with user define name. If User can use the special character then i want to replace that special character with my specific string. i found the method like this.
String replaceString(String string) {
return string.replaceAll("special_char","");
}
but how to use this method.?
relpaceAll method is required regular expression and replace string.
string.replaceAll("regularExpression","replaceString");
You can use this regular expression :
"[;\\/:*?\"<>|&']"
e.g.
String replaceString(String string) {
return string.replaceAll("[;\\/:*?\"<>|&']","replaceString");
}
Try
regular expression
static String replaceString(String string) {
return string.replaceAll("[^A-Za-z0-9 ]","");// removing all special character.
}
call
public static void main(String[] args) {
String str=replaceString("Hello\t\t\t.. how\t\t are\t you."); // call to replace special character.
System.out.println(str);
}
output:
Hello how are you
use below function to replace your string
public static String getString(String p_value)
{
String p_value1 = p_value;
if(p_value1 != null && ! p_value1.isEmpty())
{
p_value1 = p_value1.replace("Replace string from", "Replace String to");
return p_value1;
}
else
{
return "";
}
}
example
Replace string from = "\n";
Replace String to = "\r\n";
after using above function \n is replace with \r\n
**this method make two line your string data after specific word **
public static String makeTwoPart(String data, String cutAfterThisWord){
String result = "";
String val1 = data.substring(0, data.indexOf(cutAfterThisWord));
String va12 = data.substring(val1.length(), data.length());
String secondWord = va12.replace(cutAfterThisWord, "");
Log.d("VAL_2", secondWord);
String firstWord = data.replace(secondWord, "");
Log.d("VAL_1", firstWord);
result = firstWord + "\n" + secondWord;
return result;
}
Android - How to check the existence of a string value in another comma separated string .
String all_vals = "617,618,456,1,234,5,5678,225";
String check_val= "456";
How to check like,
if (all_vals contains check_val) {
}
Convert the comma-separated string to an array with split, then convert it to a List with Arrays.asList, then use contains.
String all_vals = "617,618,456,1,234,5,5678,225";
List<String> list = Arrays.asList(all_vals.split(","));
if (list.contains(check_val)) {
}
This will prevent the false positives from just checking if the substring exists in the list with contains directly on the string all_vals, e.g. all_vals.contains("4") would return true in the direct String#contains case.
Java 8:
String all_vals = "617,618,456,1,234,5,5678,225";
String check_val= "5678";
Arrays.stream(all_vals.split(",")).anyMatch(check_val:: equals)
if(Arrays.stream(all_vals.split(",")).anyMatch(check_val:: equals)){
System.out.println("The value is present");
}
String all_vals = "617,618,456,1,234,5,5678,225";
String check_val= "5678";
int place = 1;
String[] strings = all_vals.split(",");
for (String str : strings) {
if(str.equals(check_val))
{
System.out.println("We have string in all_val on place: " + place);
}
place++;
}
String all_vals = "617,618,456,1,234,5,5678,225";
String check_val= "456";
if (all_vals.startsWith(check_val) ||
all_vals.endsWith(check_val) ||
all_vals.contains("," + check_val + ","))
{
System.out.println("value found in string");
}