Java manipulating substring/char in a string array - java

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();

Related

How to convert string of values into array?

I have a string, ie 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17. How do I get each value and convert it into an array? [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]. I can't find any suggestions about this method. Can help? I did try using regex, but it just simply remove ',' and make the string into one long sentence with indistinguishable value. Is it ideal to get value before and after ',' with regex and put it into []?
You could use following solution
String dummy = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] dummyArr = dummy.split(",");
Try this to convert string to an array of Integer.
String baseString = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] baseArray = baseString.split(",");
int[] myArray = new int[baseArray.length];
for(int i = 0; i < baseArray.length; i++) {
myArray[i] = Integer.parseInt(baseArray[i]);
}
Java provides method Split with regex argument to manipulate strings.
Follow this example:
String strNumbers= "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] strNumbersArr= strNumbers.split(",");
You can convert an array of string in array of integer with Streams
int[] numbersArr = Arrays.stream(strNumbersArr).mapToInt(Integer::parseInt).toArray();
Use String.split() and you will get your desired array.
String s1="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] mumbers=s1.split(","); //splits the string based on comma
for(String ss:numbers){
System.out.println(ss);
}
See the working Example
String csv = "Apple, Google, Samsung";
String[] elements = csv.split(",");
List<String> fixedLenghtList = Arrays.asList(elements);
ArrayList<String> listOfString = new ArrayList<String>(fixedLenghtList);
//ouput
[Apple, Google, Samsung]
if you want an int array
String s = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17";
String[] split = s.split(",");
int[] result = Arrays.stream(split).mapToInt(Integer::parseInt).toArray();

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;

String into char on 2D array (java)

I am trying to fill a 2D char array with 5 words. Each string must be split into single characters and fill one row of the array.
String str = "hello";
char[][] words = new char[10][5];
words[][] = str.toCharArray();
My error is at the 3rd line I don't know how to split the string "hello" into chars and fill only the 1st row of the 2-dimensional array
If you want the array to fill the first row, just asign it to the first row:
words[0] = str.toCharArray();
Since this will create a new array in the array, you should change the instantiation of words to this:
char[][] words = new char[5][];
Java has a String class. Make use of it.
Very little is known of what you want with it. But it also has a List class which I'd recommend as well. For this case, I'd recommend the ArrayList implementation.
Now onto the problem at hand, how would this code look now?
List<String> words = new ArrayList<>();
words.add("hello");
words.add("hello2");
words.add("hello3");
words.add("hello4");
words.add("hello5");
for (String s : words) {
System.out.println(s);
}
For your case if you are stuck with using arrays.
String str="hello";
char[][] words = new char[5][];
words[][] = str.toCharArray();
Use something along the line of
String str = "hello";
char[][] words = new char[5][];
words[0] = str.toCharArray();
for (int i = 0; i < 5; i++) {
System.out.println(words[i]);
}
However, why invent the wheel again? There are cases however, more can be read on the subject here.
Array versus List<T>: When to use which?

Converting Every Other Char to Upper Case i.e. abcd --> aBcD

So I'm just starting to learn Java this afternoon. What would be the best way of doing this? And what have I done wrong? At the moment, I just get no output :(
import java.util.Scanner;
class ClassA {
public static void main(String[] args) {
Scanner MyScan = new Scanner(System.in);
System.out.print("Enter Word: ");
String UI = MyScan.nextLine();
UI.toLowerCase();
String s;
String word = "";
for (int i = 0; i <= UI.length()-1; i++) {
s = UI.substring(i, i+1);
if (i % 2 == 1) {
s.toUpperCase();
}
word.concat(s);
}
System.out.print(word);
MyScan.close();
}
}
Strings in java are immutable. This means that whatever modifying operations you call on a String, you need to assign its result to the original value in order to actually modify it.
So in your case you should type word = word.concat(s) instead of simply word.concat(s). word.concat(s) creates a new instance and unless you assign it to word, its value will remain intact.
You need to assign the values of the case conversions and the concatenation to create a new instance of the string as strings are immutable in java. change the following lines as shown.
UI = UI.toLowerCase();
s = s.toUpperCase();
word = word.concat(s);
Here's an alternate implementation -- it uses StringBuffer for concatenation, and deals with each character as a character instead of a String
`
public static String everyOtherLowerCase(String input) {
input = input.toLowerCase();
StringBuffer result = new StringBuffer("");
for(int x=0; x<input.length(); x++) {
Character c = input.charAt(x);
if(x % 2 == 0) result.append(c);
else result.append(Character.toUpperCase(c));
}
return result.toString();
}
`
As others have pointed out, Strings are immutable; it's best for performance reasons to append to a StringBuffer rather than constantly re-creating and re-allocating String objects. This is a pretty common performance mis-step in java.
The other answers are correct, but I'm going to have a stab at making it clearer.
Strings are immutable meaning that you cannot change them. But you can make a new String and assign it to the same variable. None of the methods of String change the content. Many of them return a new String. So:
String s = "Hello";
s.replace("H","J");
... creates a new String of "Jello", then throws it away.
String s1 = "Hello";
String s2 = s.replace("H","J");
... creates a new String of "Jello", and assigns it to s2.
String s1 = "Hello";
s1 = s1.replace("H","J");
... creates a new String of "Jello", assigns it to s1, throwing away the old String ("Hello") previously assigned to s1.
The class StringBuilder exists for the occasions when you do want to modify a sequence of characters in-place.
StringBuilder sb = new StringBuilder("Hello");
sb.replace(0,1,"J");
... makes sb contain "Jello" instead of "Hello".
This knowledge should give you what you need to fix your program.

Remove all non alphabetic characters from a String array in java

I'm trying to write a method that removes all non alphabetic characters from a Java String[] and then convert the String to an lower case string. I've tried using regular expression to replace the occurence of all non alphabetic characters by "" .However, the output that I am getting is not able to do so. Here is the code
static String[] inputValidator(String[] line) {
for(int i = 0; i < line.length; i++) {
line[i].replaceAll("[^a-zA-Z]", "");
line[i].toLowerCase();
}
return line;
}
However if I try to supply an input that has non alphabets (say - or .) the output also consists of them, as they are not removed.
Example Input
A dog is an animal. Animals are not people.
Output that I'm getting
A
dog
is
an
animal.
Animals
are
not
people.
Output that is expected
a
dog
is
an
animal
animals
are
not
people
The problem is your changes are not being stored because Strings are immutable. Each of the method calls is returning a new String representing the change, with the current String staying the same. You just need to store the returned String back into the array.
line[i] = line[i].replaceAll("[^a-zA-Z]", "");
line[i] = line[i].toLowerCase();
Because the each method is returning a String you can chain your method calls together. This will perform the second method call on the result of the first, allowing you to do both actions in one line.
line[i] = line[i].replaceAll("[^a-zA-Z]", "").toLowerCase();
You need to assign the result of your regex back to lines[i].
for ( int i = 0; i < line.length; i++) {
line[i] = line[i].replaceAll("[^a-zA-Z]", "").toLowerCase();
}
It doesn't work because strings are immutable, you need to set a value
e.g.
line[i] = line[i].toLowerCase();
You must reassign the result of toLowerCase() and replaceAll() back to line[i], since Java String is immutable (its internal value never changes, and the methods in String class will return a new String object instead of modifying the String object).
As it already answered , just thought of sharing one more way that was not mentioned here >
str = str.replaceAll("\\P{Alnum}", "").toLowerCase();
A cool (but slightly cumbersome, if you don't like casting) way of doing what you want to do is go through the entire string, index by index, casting each result from String.charAt(index) to (byte), and then checking to see if that byte is either a) in the numeric range of lower-case alphabetic characters (a = 97 to z = 122), in which case cast it back to char and add it to a String, array, or what-have-you, or b) in the numeric range of upper-case alphabetic characters (A = 65 to Z = 90), in which case add 32 (A + 22 = 65 + 32 = 97 = a) and cast that to char and add it in. If it is in neither of those ranges, simply discard it.
You can also use Arrays.setAll for this:
Arrays.setAll(array, i -> array[i].replaceAll("[^a-zA-Z]", "").toLowerCase());
Here is working method
String name = "Joy.78#,+~'{/>";
String[] stringArray = name.split("\\W+");
StringBuilder result = new StringBuilder();
for (int i = 0; i < stringArray.length; i++) {
result.append(stringArray[i]);
}
String nameNew = result.toString();
nameNew.toLowerCase();
public static void solve(String line){
// trim to remove unwanted spaces
line= line.trim();
String[] split = line.split("\\W+");
// print using for-each
for (String s : split) {
System.out.println(s);
}

Categories