Java program to extract substring from related strings

Within my JavaScript code, I am dealing with two string arrays:

var names = [name1, name2, name3, name4];
var values = [value1, value2, value3, value4];

To send these array values to the backend, I have created strings as shown below:

var nameString = "name1,name2,name3,name4";
var valuesString = "value1,value2,value3,value4";

Upon receiving these strings on the Java side, I need a way to remove a particular name from the nameString and ensure that the corresponding value is removed from the valueString. Is there an optimized method to achieve this in Java?

For example, if I want to remove name3, the updated strings should look like this:
  On the Java side:   
     String nameString = "name1,name2,name4";
     String valueString = "value1,value2,value4";

Answer №1

When using JavaScript:

var data = {name1:value1, name2:value1, name3:value1, name4:value1};

You may need to quote the object and then send it as JSON to be parsed in Java. http://www.json.org/java/

As I am not a Java developer, I cannot provide specific code examples, but the method is similar across all languages.

Answer №2

One way to achieve this functionality in Java is demonstrated below:

public static void main(String[] args) {
    String names = "Alice, Bob, Charlie, David";
    String values = "25, 30, 35, 40";

    names = removeElement(names, 1);
    values = removeElement(values, 1);

    System.out.println(names);
    System.out.println(values);

}

private static String removeElement(String value, int index){
    String[] array = value.split(",");
    String[] newArray = new String[array.length-1];

    System.arraycopy(array, 0, newArray, 0, index);
    System.arraycopy(array, index+1, newArray, index, array.length-1-index);

    value = convertArrayToString(newArray);

    return value;
}

private static String convertArrayToString(String[] array){
    StringBuilder result = new StringBuilder();
    for (int i=0; i<array.length; i++) {
        if(i==0){
            result.append(array[i]);
        }else{
            result.append(",").append(array[i]);
        }
    }
    return result.toString();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Learn how to calculate the total value of a dynamic text box within an ng-repeat loop

I am currently working on a form that dynamically generates number input fields within an ng-repeat loop. Users have the ability to add as many fields as they want by clicking on the "add" button. I now need to calculate the total sum of all values enter ...

Success callbacks parsed from AJAX requests

When dealing with a Backbone object and making an AJAX call to save it, I often wonder about the different ways the success callback can be handled. Sometimes, I see a generic success: function (data) { console.log(data); Other times, it's more spec ...

Is it possible to send multiple HTML input values to a Google Spreadsheet using only JavaScript?

Seeking a faster and more efficient way to send the values of multiple HTML Inputs to a specific location in a Google Spreadsheet? The existing script takes too long to complete, often skips inputs, and relies heavily on "google.script.run". Due to softwar ...

The Firebase promise resolves before the collection is refreshed

Currently utilizing AngularFire for my project. I wrote some code to add a new record to an array of records and planned on using the promise then function to update the array with the most recent datestamp from the collection. this.addRecord = function() ...

Can Selenium in JavaScript be used to retrieve child elements from a webpage?

I've been struggling to adapt my JavaScript script for use with Selenium (also in JavaScript). Despite numerous attempts, I haven't been able to find a solution. I've attached an image to better explain my question await chromeDriver.findEle ...

JQuery: Issues with attaching .on handlers to dynamically added elements

I'm currently developing a comment system. Upon loading the page, users will see a box to create a new comment, along with existing comments that have reply buttons. Clicking on a reply button will duplicate and add the comment text box like this: $( ...

Generating a dynamic form by utilizing a JavaScript JSON object

I need assistance with creating an html form based on a JSON object’s properties. How can I target multiple levels to generate different fields and also drill down deeper to access field details? I am open to suggestions for alternative formats as well. ...

Adjust a sub-document field using mongoose

My foundational structure var GameChampSchema = new Schema({ name: String, gameId: { type: String, unique: true }, status: Number, countPlayers: {type: Number, default: 0}, companies: [ { name: String, login: String, pass: ...

Is there a way to make the submit button navigate to the next tab, updating both the URL and the tab's content as well?

I am encountering an issue with my tabs for Step1 and Step2. After pressing the submit button in Step1, the URL updates but the component remains on tab1. How can I resolve this so that the user is directed to the Step2 tab once they click the submit butto ...

Retrieve the element from the most recent append() function invocation

Is it possible to change the chain context to a new DOM node when using append() to insert it? Here is an example code snippet demonstrating this: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org ...

When the field name is clicked, retrieve it and display it in a TOAST message

I am currently trying to extract information from a list displayed below (using onClick) where the data is retrieved from a JSON file and consists only of strings. However, I am facing difficulties in properly linking the array elements with the onClick fu ...

Creating an AJAX URL in an external JavaScript file within a Django project

How can I verify if a student user's email exists in the database using keyup event in a registration form, and prevent form submission if the email is already registered? Below are the relevant files for achieving this: urls.py urlpatterns = [ ...

Guide on transferring an array generated within a child jQuery function back to the parent function in JavaScript

How can I effectively retrieve an array created in a jQuery function and return it as the output of my parent function? Here is the basic structure: function getFlickrSet(flickr_photoset_id){ var images = []; images = $.getJSON(url, function(data){ ...

Dealing with encoding problems in Node.JS when parsing JSON data with UTF-

I have developed a small script that allows me to fetch keyword suggestions from the Google search API. One major issue I am facing is when the response contains special characters (such as à é ù etc.): my application returns unreadable keywords like: ...

Error: The property 'combine' of 'winston_1.default.format' cannot be destructured since it is not defined

Encountered an error while using Winston in Node.js, how can we resolve it? The version of Winston I am using is 3.3.3 and winston-daily-rotate-file version is 4.5.0 I attempted npm i winston@next --save, but the error persists. ** Here is the Error Mes ...

Every time I try to use the EJS syntax, particularly when I use the 'include' function, the page just won't load

There seems to be an issue with the page loading - it only works once or twice, if I'm lucky. However, when I remove the EJS syntax from the file and just leave the HTML, it loads without any problems. I can't seem to figure out why this is happe ...

Assistance with setting up a Java sockets server

Greetings! I am a complete beginner in Java programming and I am facing a challenge with setting up a socket server and client as per my requirements. The issue I am encountering is as follows: Server: Currently, I am monitoring the output from the clie ...

Mastering Checkbox Features Using KnockoutJS

This unique checkbox functionality goes beyond simply setting it based on existing data. The page must also react in multiple ways when the user manually checks or unchecks it. Picture having a murderCaseModel containing a list of different Witnesses to a ...

What's preventing the threads from running simultaneously?

I am currently working on a simple multi-threading program. Main program package javathread; public class JavaThread { public static void main(String[] args) { JThread t1 = new JThread(10,1); JThread t2 = new JThread(10,2); ...

Is it better to use regexp.test or string.replace first in my code?

When looking to replace certain parts of a string, is it better to use the replace method directly or first check if there is a match and then perform the replacement? var r1 = /"\+((:?[\w\.]+)(:?(:?\()(:?.*?)(:?\))|$){0,1})\ ...