Array values do not update - java

I am trying to use the string after I passed it through my cleanUp function. When I return the arguments it no longer keeps the same value.
My initial strings have punctuations.
I pass the strings to a method to clean up the punctuations.
I return the modified strings back to my main method.
I print out the modified string but my results have returned to the original value of the string.
public class test{
public static void main(String[] args){
String str1 = "this-is.first:sentence/.";
String str2 = "this=is.second:sentece.";
String[] arr = cleanUp(str1, str2);
for (String string : arr){
System.out.println("string after cleanup()" + string);
}
}
public static String[] cleanUp(String str1, String str2) {
String[] arr = {str1, str2};
for (String string : arr){
string = string.replaceAll("\\p{Punct}","");
System.out.println("string cleaned:" + string);
}
return new String[] {str1, str2};
}
}
Current Output:
string cleaned: this is first sentence
string cleaned: this is second sentece
string after cleanup(): this-is.first:sentence/.
string after cleanup(): this=is.second:sentece.
Expected Output:
string cleaned: this is first sentence
string cleaned: this is second sentece
string after cleanup(): this is first sentence
string after cleanup(): this is second sentece

You have two issues in your code which have to do with the fact that Java is pass-by-value.
You are re-assigning your local string variable in the loop, not what is inside the array. So string has the correct value, the string in array still has the old value.
Your output is build out of string1 and string2 which you did never update. Your updated content is supposed to be in the arr array you built using your loop. So you must either update the values based on the arrays content or return the arrays content or directly the array
Here is a fixed version:
public static String[] cleanUp(String str1, String str2) {
String[] arr = { str1, str2 };
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i].replaceAll("\\p{Punct}", "");
System.out.println("string cleaned:" + arr[i]);
}
return arr;
}

A Java String is immutable, and when you use the for-each loop it hides your iterator. Basically, your current code is almost correct but instead of using a for-each loop and locally modifying a temporary String, use a regular loop and modify the array you generate on the first line. Also, you should return that array instead of creating a new one. And, I assume you wanted to keep some white-space in your output. Something like,
public static String[] cleanUp(String str1, String str2) {
String[] arr = { str1, str2 };
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i].replaceAll("\\p{Punct}", " ").replaceAll("\\s+", " ");
System.out.println("string cleaned:" + arr[i]);
}
return arr;
}
Which I tested with your other code (and it returns)
string cleaned:this is first sentence
string cleaned:this is second sentece
string after cleanup()this is first sentence
string after cleanup()this is second sentece

Related

Why am I getting variable not initialized error?

I am trying to get all the characters from a string to a 2D character array. The details are given below:
My code:
import java.util.*;
public class Main
{
public static void main(String[] args) {
//System.out.println("Hello World");
Scanner sc=new Scanner(System.in);
int n,l=0; //as you can see, n is initialized
String x="";
char[][] arr1=new char[10][10];
if(sc.hasNextInt())
n=sc.nextInt();
for(int i=0;i<n;i++){
if(sc.hasNextLine())
x=sc.nextLine();
//char[] arr=x.toCharArray();
if(x.length()==n){
for(int j=l;j<arr1.length;j++){
for(int k=0;k<arr1.length;k++){
arr1[j][k]=x.charAt(i);
}
x="";
++l;
break;
}
}
}
System.out.println(arr1);
}
}
Error:
error: variable n might not have been initialized
for(int i=0;i<n;i++){
What's this? Variable n is already initialized. How do I fix this?
You can only replace a char with a char or a CharSequence with a CharSequence (as those are the only overloads defined for String#replace), not a char with a String. Converting the first argument to a String (which is a CharSequence) with String.valueOf will solve the issue.
ar[j] = ar[j].replace(String.valueOf(ar[i].charAt(k)), "");
If you are allowed to use Java 8 stream API, method simplify may be presented as follows:
using Stream reduce operation to join strings in the input array
using String replaceAll method with a regexp replacing all previously detected characters with empty literal:
public static String simplify(String... arr) {
return Arrays
.stream(arr)
.reduce("", // empty accumulator
(s1, s2) -> s1 + (s1.isEmpty() ? s2 : s2.replaceAll("[" + s1 + "]", ""))
);
}
Tests:
System.out.println(simplify("abcdef", "fghij"));
System.out.println(simplify("abcdef", "fghij", " jklmn"));
Output
Online demo
abcdefghij
abcdefghij klmn

Trying to retrieve the first longest word from a string, where a sentence contains strings of the same length ?

public class Challenge{
public static String longestWord(String sentence){
String s= sentence;
String[] word=s.split(" ");
String four=" ";
for(int i=0;i<word.length;i++){
if(word[i].length()>=four.length()){
four=word[i];
}
}
return four;
}
What i'm struggling with here is that if i have the sentence "This has lots that are four long" for example, the code defaults to printing "four" instead of "this" which i need - im not sure how to implement the code which allows me to return the first longest string from a given sentence. Any help would be appreciated.
You just need to stop overwriting your stored “longest word” when the length is equal to the current word. Replacing >= with > in your if statement should do the trick.
Your variable names are confusing, and redundant. I would assume the longest word is the first, and then begin the loop at the second word. And you want > (not >=). Like,
public static String longestWord(String sentence) {
String[] words = sentence.split("\\s+");
String longest = words[0];
for (int i = 1; i < words.length; i++) {
if (words[i].length() > longest.length()) {
longest = words[i];
}
}
return longest;
}
or in Java 8+
public static String longestWord(String sentence) {
return Stream.of(sentence.split("\\s+")).max(
(a, b) -> Integer.compare(a.length(), b.length())).get();
}
You can try in Java 8:
public static String longestString(String sentence){
return Stream.of(sentence.split("\\s+"))
.max(Comparator.comparing(String::length))
.orElse("");
}

Java String With Spaces

and thank you for helping me.
So my question is i need a code that asks you for a String like "1234 567" (input), then returns the string numbers like "1 2 3 4 5 6 7" (output) once more
my current code is:
public class StringComEspaços {
public static String formatNumberWithSpaces(String inputString) {
String outputString = "222";
return outputString;
}
public static void main(String[] args) {
System.out.println(formatNumberWithSpaces("123 222 2222"));
}
}
thanks for the help, and sorry for bad english :).
There are many possible ways to solve your problem.
You can do it in an OO way with StringBuilder:
public static String formatNumberWithSpaces(String inputString) {
StringBuilder output = new StringBuilder();
for (char c : inputString.toCharArray()) // Iterate over every char
if (c != ' ') // Get rid of spaces
output.append(c).append(' '); // Append the char and a space
return output.toString();
}
Which you can also do with a String instead of the StringBuilder by simply using the + operator instead of the .append() method.
Or you can do it a more "modern" way by using Java 8 features - which in my opinion is fun doing, but not the best way - e.g. like this:
public static String formatNumberWithSpaces(String inputString) {
return Arrays.stream(input.split("")) // Convert to stream of every char
.map(String::trim) // Convert spaces to empty strings
.filter(s -> !s.isEmpty()) // Remove empty strings
.reduce((l, r) -> l + " " + r) // build the new string with spaces between every character
.get(); // Get the actual string from the optional
}
Just try something that works for you.
Try out this function:
public static String formatNumberWithSpaces(String inputString){
String outputString = ""; //Declare an empty String
for (int i = 0;i < inputString.length(); i++){ //Iterate through the String passed as function argument
if (inputString.charAt(i) != ' '){ //Use the charAt function which returns the char representation of specified string index(i variable)
outputString+=inputString.charAt(i); //Same as 'outputString = outputString + inputString.charAt(i);'. So now we collect the char and append it to empty string
outputString+=' '; //We need to separate the next char using ' '
} //We do above instruction in loop till the end of string is reached
}
return outputString.substring(0, outputString.length()-1);
}
Just call it by:
System.out.println(formatNumberWithSpaces("123 222 2222"));
EDIT:
Or if you want to ask user for input, try:
Scanner in = new Scanner(System.in);
System.out.println("Give me your string to parse");
String input = in.nextLine(); //it moves the scanner position to the next line and returns the value as a string.
System.out.println(formatNumberWithSpaces(input)); // Here you print the returned value of formatNumberWithSpaces function
Don't forget to import, so you will be able to read user input :
import java.util.Scanner;
There are various ways to read input from the keyboard, the java.util.Scanner class is one of them.
EDIT2:
I changed:
return outputString;
..to: return outputString.substring(0, outputString.length()-1);
Just because outputString+=' '; was also appending empty space at the end of string, which is useless. Didn't add an if inside for loop which wouldn't add space when last char is parsed, just because of its low performance inside for loop.
use this code.
public class StringComEspaços {
public static void main(String[] args) {
System.out.println(formatNumberWithSpaces("123 222 2222"));
}
private static String formatNumberWithSpaces(String string) {
String lineWithoutSpaces = string.replaceAll("\\s+", "");
String[] s = lineWithoutSpaces.split("");
String os = "";
for (int i = 0; i < s.length; i++) {
os = os + s[i] + " ";
}
return os;
}
}

Split String To Array

I've been trying to split an string by a character and store each split value inside an array.
In C# it can be done by calling the .ToArray() method after the Split() but such method apparently doesn't exits in Java. So I've been trying to do this like this (rs is a string list with elements separated by #) :
String t[] = new String[10];
for (int i = 0; i < rs.size(); i++) {
t = null;
t = rs.get(i).split("#");
}
But the whole split line is passed to an index of the array like:
String x = "Hello#World" -> t[0] = "Hello World" (The string is split in one line, so the array will have only one index of 0)
My question is that how can store each spit element in an index of the array like :
t[0] = "Hello"
t[1] = "World"
It sounds like your trying to loop through a list, split them then add the arrays together? What your defining as the problem with the .split method is exactly what the split method does.
ArrayList<String> rs = new ArrayList<>();
rs.add("Hello#World");
rs.add("Foo#Bar#Beckom");
String [] t = new String[0];
for(int i=0;i<rs.size();i++) {
String [] newT = rs.get(i).split("#");
String [] result = new String[newT.length+t.length];
System.arraycopy(t, 0, result, 0, t.length);
System.arraycopy(newT, 0, result, t.length, newT.length);
t = result;
}
for(int i=0;i<t.length;i++) {
System.out.println(t[i]);
}
Works just find output is:
Hello
World
Foo
Bar
Beckom
public class Test {
public static void main(String[] args) {
String hw = "Hello#World";
String[] splitHW = hw.split("#");
for(String s: splitHW){
System.out.println(s);
}
}
}
This produced following output for me:
Hello
World
Try this way:
String string = "Hello#World"
String[] parts = string.split("#");
String part1 = parts[0]; // Hello
String part2 = parts[1]; // World
It is always good to test beforehand if the string contains a #(in this case), just use String#contains().
if (string.contains("#")) {
// Split it.
} else {
throw new IllegalArgumentException(message);
}
why are you using a loop when the problem is already solved in java..
try this
String x = "Hello#World";
String[] array = x.split("#", -1);
System.out.println(array[0]+" "+array[1]);

Filter out all instances of one string from another string in java

I want to create a method called filterOut that accepts two string as arguments and returns the first string with all instances of the second string removed. Ex: filterOut("hello my friend, how are you?" , "h"); returns "ello my friend, ow are you?" and filterOut("abchelloabcfriendabc" , "abc"); returns "hellofriend"
public static String filterOut(String phrase, String second){
int counter = 0;
int length = phrase.length();
String filtered = "";
while(counter < length){
String letter = phrase.substring(counter, counter + 1);
if(!letter.equals(second)){
filtered = filtered + letter;
}
counter++;
}
return filtered;
public static void main(String args[]){
String next = filterOut("hello my friend, how are you?" , "h");
System.out.println(next);
}
This code only works for the first example when I use it in the main method. How can I get it to work for the second example as well?
You can simply do:
str1.replace(str2, "");
Or in your example,
second.replace(phrase, "");
Also: there is no need to write a method for this, when there already is one :-)
You can use replace
public static String filterOut(String phrase) {
return phrase.replace(phrase, "");
}
Edit:
You can also use split method
public static String filterOut(String phrase, String second) {
String filtered = "";
for (String each : phrase.split(second)) {
filtered = filtered + each;
}
return filtered;
}
Your method wont work because you are comparing character by character in the below line. So that's why it will work for filterOut("hello my friend, how are you?" , "h"); and not work for input filterOut("abchelloabcfriendabc" , "abc");
String letter = phrase.substring(counter, counter + 1);
if(!letter.equals(second)){
filtered = filtered + letter;
}

Categories