How to add new text to string without removing old string text? - java

Suppose I have a string String text = ""; and I add a text to it
text = "Apple";
now I want it not to remove the old String when I add a new one, like this
text = "Banana";
text = "Orange";
The output should be Apple, Banana, Orange, but the output i'm getting is Orange. How to do that in java?

Since String is Immutable then you can't edit t without reassigning it, however there is something called StringBuilder it is mutable so it can be changed.
String original=new String("blabla")
StringBuilder builder=new StringBuilder(myString);
original will not be affected expect if did you re assign it, but because of String builder is mutable you can do something like the following
builder.appened("someData");
and it should be retrieved as string like this
String newString=builder.toString()

You want the variable to hold multiple Strings. Yet, you don't want to append the String. A data structure is what you are looking for.
In this case, ArrayList can fulfill your needs:
ArrayList<String> texts = new ArrayList<String>();
texts.add("Apple");
texts.add("Banana");
texts.add("Orange");
You can get the elemebt by the order you added the Strings with index beggining with 0:
Systen.out.println(texts.get(0)); // prints "Apple"
To print all the elements from the ArrayList:
System.out.println(texts); // prints "Apple, Banana, Orange"

There are 2 ways you can achieve your desired output/result:
1. Using String:
You can simply append the new values at the end of String as following...
String text = "";
text = "Apple";
text = text + ", "+ "Banana";
text = text + ", "+ "Orange";
System.out.println(text); //output will be: Apple, Banana, Orange
2. Using StringBuilder: [recommended]
You can initialize StringBuilder, and use append() function to append new values at the end of the String and at last, you can get String from StringBuilder using toString() method of StringBuilder.
StringBuilder builder = new StringBuilder("");
builder.append("Apple").append(", ").append("Banana").append(", ").append("Orange");
String text = builder.toString();
System.output.println(text); //output will be Apple, Banana, Orange
2nd approach is recommended because when you append a String in StringBuilder, it does not create new object of String in String pool every time, it updates the existing object of StringBuilder.
Whereas String class in Java is immutable, so when you append a String in String literal, then it does update the existing object, it does create new object of String in String pool and points the reference to newly created String pool object.

Related

Java manipulating substring/char in a string array

I have a string array in JAVA like:
String[] fruits = {"banana", "apple", "orange"};
How can I access to a character/substring of a string member? For example I want to show the second character of first member "banana" which is 'a' and change it to 'b'. Should I make a new string equal to my array member, do the manipulation and assign the new string to my array list like this:
string manipulate = fruits[0];
//do manipulation on 'manipulate' then:
fruits[0] = manipulate;
or there is a builtin or better way?
Thanks
Java's Strings are immutable, meaning you can't change them. Instead, as #AshishSingh notes in the comments, you'll need to create a new String.
Just do this:
fruits[0] = manipulate(fruits[0]);
Here, manipulate() is your function which takes an input string, manipulates it however you want, and then returns the manipulated string.
public String manipulate(String oldStr) {
StringBuilder newStr = new StringBuilder(oldStr);
newStr.setChar(1, 'b')
return newStr.toString();
}
I'm using StringBuilder which is a mutable object, so can have elements reassigned. I set the second character to 'b' and then return the new String.
The Java String object is immutable, so you can't modify its internal value.
char charArray[] = fruits[index].toCharArray();
charArray[2] = 'b';
After modifying the elements in the character array, put it back into fruits array.
fruits[index] = String.valueOf(charArray);
The existing fruits[index] will be replaced by the new String.
If you want to access a particular character of a String, use, String.charAt(index).
That said, you cannot change a character in a String because Strings are immutable in Java.
If you want to change a character in a given String, you will actually have to create a new String.
Example :
String[] fruits = {"banana", "apple", "orange"};
String banana = fruits[0];
char[] chars = banana.toCharArray();
chars[0] = 'c';
chars[4] = 'd';
String newStr = String.valueOf(chars);
System.out.println(newStr);
Output :
canada
This is how you can do it.
int indexOfArray=1;
int indexOfString=1;
char charToChange='x';
String fruits[] = {"banana", "apple", "orange"};
StringBuilder manipulate = new StringBuilder(fruits[indexOfArray]);
manipulate.setCharAt(indexOfString, charToChange);
fruits[indexOfArray]=manipulate.toString();

Storing multiple values in Java without using arrays

Take user input for 5 times, store them in a variable and display all 5 values in last. How can I do this in Java? Without using arrays, collections or database. Only single variable like String and int.
Output should look like this
https://drive.google.com/file/d/0B1OL94dWwAF4cDVyWG91SVZjRk0/view?pli=1
This seems like a needless exercise in futility, but I digress...
If you want to store them in a single string, you can do it like so:
Scanner in = new Scanner(System.in);
String storageString = "";
while(in.hasNext()){
storageString += in.next() + ";";
}
if you then input foo bar baz storageString will contain foo;bar;baz;. (in.next() will read the input strings to the spaces, and in.hasNext() returns false at the end of the line)
As more strings are input, they are appended to the storageString variable. To retrieve the strings, you can use String.split(String regex). Using this is done like so:
String[] strings = storageString.split(";");
the strings array which is retrieved here from the storageString variable above should have the value ["foo", "bar", "baz"].
I hope this helps. Using a string as storage is not optimal because JVM creates a new object every time a string is appended onto it. To get around this, use StringBuilder.
*EDIT: I originally had said the value of the strings array would be ["foo", "bar", "baz", ""]. This is wrong. The javadoc states 'Trailing empty strings are therefore not included in the resulting array'.
public static void main(String[] args) {
String s = "";
Scanner in = new Scanner(System.in);
for(int i=0;i<5;i++){
s += in.nextLine();
}
System.out.println(s);
}
Why dont you use Stingbuilder or StringBuffer, keep appending the some delimiter followed by the input text.
Use simple String object and concatenate it with new value provided by user.
String myString = "";
// while reading from input
myString += providedValue;

Properly formatting output of arraylist data?

I have a method in my switch statement explaining to print my arraylist
(i.e - System.out.println(drinkList);)
ArrayList<String> drinkList = new ArrayList<String>();
System.out.print("Please enter a drink information to add:\n");
inputInfo = scan.nextLine().trim();
drinkLink = DrinkParser.parseStringToDrink(inputInfo);
drinkList.add(drinkLink.toString()); //Take in user data to parse into parts
Then I called it using the code
System.out.println(drinkList);
My problem is the output prints the following as such:
[
Data Entry 1
,
Data Entry 2
]
I want to remove the brackets and the comma.
Don't call the toString() method on the ArrayList but loop through it and build a string yourself. Do something like:
StringBuilder builder = new StringBuilder();
for (String value : drinkList) {
builder.append(value) + ",";
}
String text = builder.toString();
System.out.println(text);
That'll make sure that the resulting string has the format that you want - in this case comma-separated entries.
Use the following code to remove the brackets and the commas:
String s = "[\nData Entry 1\n,\n Data Entry 2\n]";
String result = s.replaceAll("[^\\dA-Za-z\n]", "");
System.out.println(result);
The result is:
Data Entry 1
Data Entry 2
Or, you can override toString() method for your class.

Concatenate a new string at the beginning of an existing string

i want to concatenate a new string to the start of an existing string, for example,
the current string="" and i want always to concatenate the new string to start of my old string:
String msg="Java One",temp;
for(int i=msg.length()-2;i>0;i--){
here i make a loop starting from the end of msg after the end finishes temp should contains "Java One" but in this order
e
ne
one
a one
va one
}
and so on
I want always to concatenate the new string to start of my old string
This is very simple, but not very efficient:
String oldString = "";
for (...) {
// Prepare your new string
String newString = ... ;
// Add the new string at the beginning of the old string
oldString = newString + oldString;
}
You can use String#substring(int,int) to get different substrings in each iteration.
for(int i=msg.length()-1;i>=0;i--){
System.out.println(msg.substring(i,msg.length()));
}
Of course you can store each generated substring and do what you wish with it.
Note that this approach is likely to be more efficient, because though new String objects will be created, it is likely to use the same underlying char[] object for all of them.
Also note that we are iterating from msg.length()-1 (and not -2, as the original code in the question) and while i >= 0 (and not i > 0, as in the original question)

How to including variables within strings? [duplicate]

This question already has answers here:
Named placeholders in string formatting
(23 answers)
Closed 1 year ago.
So, we all should know that you can include variables into strings by doing:
String string = "A string " + aVariable;
Is there a way to do it like:
String string = "A string {aVariable}";
In other words: Without having to close the quotation marks and adding plus signs. It's very unattractive.
You can always use String.format(....). i.e.,
String string = String.format("A String %s %2d", aStringVar, anIntVar);
I'm not sure if that is attractive enough for you, but it can be quite handy. The syntax is the same as for printf and java.util.Formatter. I've used it much especially if I want to show tabular numeric data.
This is called string interpolation; it doesn't exist as such in Java.
One approach is to use String.format:
String string = String.format("A string %s", aVariable);
Another approach is to use a templating library such as Velocity or FreeMarker.
Also consider java.text.MessageFormat, which uses a related syntax having numeric argument indexes. For example,
String aVariable = "of ponies";
String string = MessageFormat.format("A string {0}.", aVariable);
results in string containing the following:
A string of ponies.
More commonly, the class is used for its numeric and temporal formatting. An example of JFreeChart label formatting is described here; the class RCInfo formats a game's status pane.
Since Java 15, you can use a non-static string method called String::formatted(Object... args)
Example:
String foo = "foo";
String bar = "bar";
String str = "First %s, then %s".formatted(foo, bar);
Output:
"First foo, then bar"
Apache Commons StringSubstitutor can be used.
import org.apache.commons.text.StringSubstitutor;
// ...
Map<String, String> values = new HashMap<>();
values.put("animal", "quick brown fox");
values.put("target", "lazy dog");
StringSubstitutor sub = new StringSubstitutor(values);
String result = sub.replace("The ${animal} jumped over the ${target}.");
// "The quick brown fox jumped over the lazy dog."
This class supports providing default values for variables.
String result = sub.replace("The number is ${undefined.property:-42}.");
// "The number is 42."
To use recursive variable replacement, call setEnableSubstitutionInVariables(true);.
Map<String, String> values = new HashMap<>();
values.put("b", "c");
values.put("ac", "Test");
StringSubstitutor sub = new StringSubstitutor(values);
sub.setEnableSubstitutionInVariables(true);
String result = sub.replace("${a${b}}");
// "Test"
you can use String format to include variables within strings
i use this code to include 2 variable in string:
String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);

Categories