How to add "-" in between two stings on Android? - java

Example:
cname = "name"
ccurt = "last name"
Required output = name - last name
But current output = namelast name
How to get output as above? The used code is below for your reference,
Code used:
long id= AddDbHelper.createReminder(cname +ccurt,de,reminderDateTime);

use
String output=cname+"-"+ccurt;

I guess you can use StringBuilder
StringBuilder tmp = new StringBuilder();
tmp.append(cname);
tmp.append("-");
tmp.append(ccurt);
String fullName = tmp.toString();
Or simply:
String fullName = new StringBuilder(cname).append(" - ").append(ccurt).toString();
StringBuilder
A modifiable sequence of characters for use in creating strings. This
class is intended as a direct replacement of StringBuffer for
non-concurrent use; unlike StringBuffer this class is not
synchronized.

Simply use
String output=cname+" - "+ccurt;

Related

How to replace two strings in only one time in java

May I know the fastest way to replace two strings in java?
Here is the sample code:
String template = "I replace {0} and {1} at one time".
String replaceZero = "Java";
String replaceOne = "C#";
template = template.replace("{0}", replaceZero).replace("{1}", replaceOne);
I have to write code like this. But I want the fastest way. Like this:
String template = "I replace {0} and {1} at one time".
tempate = template.replace("{0}{1}", replaceZero, replaceOne);
Is there any implementations to replace all strings in one time?
It looks like you may be looking for MessageFormat.format. I can't guarantee that it will work fastest, but your code should be clearer.
String template = "I replace {0} and {1} at one time";
String replaceZero = "Java";
String replaceOne = "C#";
System.out.println(MessageFormat.format(template, replaceZero, replaceOne));
Output: I replace Java and C# at one time
You could use a StringBuilder. Something like,
String template = "I replace {0} and {1} at one time";
String replaceZero = "Java";
String replaceOne = "C#";
StringBuilder sb = new StringBuilder(template);
sb.replace(sb.indexOf("{0}"), sb.indexOf("{0}") + 3, replaceZero).
replace(sb.indexOf("{1}"), sb.indexOf("{1}") + 3, replaceOne);
System.out.println(sb.toString());
I get
I replace Java and C# at one time
Are you tied to your input having "{0}" and "{1}"? Is this some kind of requirement outside your control?
If you have control of the input, then I would look at using something like:
String.format("I replace %s and %s at one time", "Java", "C#");

How to remove a substring in java

I am receiving a file path with "xyz" appended to it. name would look like D:/sdcard/filename.docxyz
i am using the below code to remove xyz but it is not working. what is missing here ?
String fileExtension = path.substring(path.lastIndexOf(".")+1);
String newExtension= fileExtension;
newExtension.replace("xyz", "");
path.replace(fileExtension, newExtension);
return path;
What is missing is that you need to save the result of your operations. Strings are immutable in Java, and the results of all String manipulations are therefore returned in the form of a new String:
newExtension = newExtension.replace("xyz", "");
path = path.replace(fileExtension, newExtension);
String in java are immutable, and changes upon it never occurs in place, but every time a new string is returned,
newExtension = newExtension.replace("xyz", "");
You could also use replaceAll() with a regex.
public static void main(String[] args) {
String s = "D:/sdcard/filename.docxyz";
System.out.println(s.replaceAll("xyz$", "")); // $ checks only the end
}
O/P :
input : s = "D:/sdcard/filename.docxyz";
D:/sdcard/filename.doc
input : String s = "D:/sdcard/filenamexyz.docxyz";
output : D:/sdcard/filenamexyz.doc
newExtension.replace("xyz", "");
Will only return string which has "xyz" removed but newExtension will remain as it is. Simple fix for your problem is use as below
String newExtension= fileExtension.replace("xyz", "");

How to concatenate a String in Java without using a complex code structure?

I have the following java code:
String strTest = null;
for (AlternativeEntity alternativeEntity : msg.Guidance()
.getAlternatives()) {
strTest = strTest + alternativeEntity.getArrivalStation().getName() + ", ";
}
The output looks like this:
nullabc, xyz, oop,
How can I solve this problem and very bad character format? It would be great if I can create output like this:
abc, xyz, oop
Initialize your string to "":
String strTest = "";
Alternatively, you should use a StringBuilder:
StringBuilder builder = new StringBuilder();
for (AlternativeEntity alternativeEntity : msg.Guidance()
.getAlternatives()) {
builder.append(alternativeEntity.getArrivalStation().getName()).append(", ");
}
This will produce better performance.
Initialize strTest as:
String strTest = "";
Also, remove the last comma ,
strTest=strTest.substring(0, strTest.length()-1);
You can use Guava's Joiner#join(Iterable parts). For example:
Joiner joiner = Joiner.on(", ").skipNulls();
String result = joiner.join(list);
System.out.println(result);
Here, all the elements of the list will be printed comma separated without any trailing commas. Also, all the null elements will be skipped.
More info:
Strings Explained
Java provides StringBuilder class just for this purpose,its simple and easy to use..
StringBuilder str = new StringBuilder("India ");
//to append "Hi"
str.append("Hi");
// print the whole string
System.out.println("The string is "+str)
the output will be : The string is India Hi
click here to know more about StringBuilder class
Replace String strTest = null; by String strTest = "";
Change
String strTest = null;
to
String strTest = "";
why don't you use:
String strTest = "";
and at the end:
if(strTest.endsWith(", "))
strTest = strTest.substring(0, strTest.length()-2);
Initialize String strTest="";
For skipping the last comma','
Use outside For loop:
strTest = strTest.substring(0,strTest.trim().length()-1);
String strTest = null;
for (AlternativeEntity alternativeEntity : msg.Guidance().getAlternatives()) {
String name = alternativeEntity.getArrivalStation().getName();
strTest = (strTest == null) ? name : strTest + ", " + name;
}
If the list is long, you should use a StringBuilder rather than the String for strTest because the code above builds a fresh string on each iteration: far too much copying.

Java: replacing characters in a String

I have a String that represents a time value and is stored in the following format:
1:31:25
I would like to replace the colons and change the format to:
1h 31m 25s
What function in Java will let me replace the first two colons with 'h ' and 'm ', and the end of the string with 's'.
You could do something like this:
String[] s = myString.split(":");
String.format("%sh %sm %ss", s);
Or even compact!
String.format("%sh %sm %ss", myString.split(":"));
String time = "1:31:25";
String formattedTime = time.replaceFirst(":","h ").replaceFirst(":","m ").concat("s");
String input = "1:31:25";
String[] tokens = input.split(":");
String output = tokens[0] + "h " + tokens[1] + "m " + tokens[2] + "s";
Repeated use of the String.replaceFirst() method would help you here.
Simply replace your first ':' with the 'h', then apply again for 'm' etc.
There are additional options, which may be more appropriate/robust etc. depending on your circumstances.
Regular expressions may be useful here, to help you parse/split up such a string.
Or given that you're parsing/outputting times, it may also be worth looking at SimpleDateFormat and its ability to parse/output date/time combinations.
In fact, if you're storing that date as a string, you may want to revist that decision. Storing it as a date object (of whatever variant) is more typesafe, will protect you against invalid values, and allow you to perform arithmetic etc on these.
String[] timeStr = "1:31:25".split(":");
StringBuffer timeStrBuf = new StringBuffer();
timeStrBuf.append(timeStr[0]);
timeStrBuf.append("h ");
timeStrBuf.append(timeStr[1]);
timeStrBuf.append("m ");
timeStrBuf.append(timeStr[2]);
timeStrBuf.append("s");
You can use a regular expression and substitution:
String input = "1:31:25";
String expr = "(\\d+):(\\d+):(\\d+)";
String substitute = "$1h $2m $3s";
String output = input.replaceAll(expr, substitute);
An alternative is to parse and output the String through Date:
DateFormat parseFmt = new SimpleDateFormat("HH:mm:ss");
DateFormat displayFmt = new SimpleDateFormat("H'h' mm\'m' ss's'");
Date d = parseFmt.parse(input);
output = displayFmt.format(d);
Use split()
String s = "1:31:25";
String[] temp = s.split(":");
System.out.println(s[0]+"h"+" "+s[1]+"m"+" "+s[2]+"s");

how to add a hyphen in between a string

I have the following sting xxxxx, I want to add a hyphen like x-xxxx, how can I do so using Java?
You can make use of String#substring().
String newstring = string.substring(0, 1) + "-" + string.substring(1);
You'll only need to check the string length beforehand to avoid IndexOutOfBoundsException, but that's nothing more than obvious.
Assuming
String in = "ABCDEF";
String out;
Then, any of:
out = in.replaceFirst(".", "$0-");
or
out = String.format("%1$s-%2$s", in.substring(0,1), in.substring(1));
or
out = in.substring(0,1) + "-" + in.substring(1);
or
out = new StringBuilder(in).insert(1, '-').toString();
will make out = "A-BCDEF".
String is an immutable type in Java, meaning that you can't change the character sequence it represents once the String is constructed.
You can use an instance of the StringBuilder class to create a new instance of String that represents some transformation of the original String. For example, add a hyphen, as you ask, you can do this:
String str = "xxxxx";
StringBuilder builder = new StringBuilder(str);
builder.insert(1, '-');
String hyphenated = builder.toString(); // "x-xxxx"
The StringBuilder initially contains a copy of the contents of str; that is, "xxxxx".
The call to insert changes the builder's contents to "x-xxxx".
Calling toString returns a new String containing a copy the contents of the string builder.
Because the String type is immutable, no manipulation of the StringBuilder's contents will ever change the contents of str or hyphenated.
You can change what String instance str refers to by doing
str = builder.toString();
instead of
String hyphenated = builder.toString();
But never has the contents of a string that str refers to changed, because this is not possible. Instead, str used to refer to a instance containing "xxxxx", and now refers to a instance containing "x-xxxx".
String xxx = "xxxxx";
String hyphened = xxx.substring(0,1) + "-" + xxx.substring(1);
You can do:
String orgStr = "xxxxx";
String newStr = orgStr.substring(0,1) + "-" + orgStr.substring(1)
Here's another way:
MaskFormatter fmt = new MaskFormatter("*-****");
fmt.setValueContainsLiteralCharacters(false);
System.out.println(fmt.valueToString("12345"));

Categories

Resources