Create a new array index if it doesn't exist - java

Say I have a String like below
String s1 = "test1=1&test2=2&test3=&test4=4";
Pls note the test3 parameter in the string S1 as it doesn't have any value
String [] splitS1 = s1.split("\\&");
for (int i = 0; i < splitS1.length; i++) {
String[] params = splitS1[i].split("=");
System.out.println("Attribute:"+params[0]+" Value : "+params [1]);
}
Above code throws java.lang.ArrayIndexOutOfBoundsException: 1 because test3 in String s1 doesn't have any value so params[1] is not valid with respect to test3.
I tried doing this
if(params.length == 1) {
params[1] = "";
}
But I know that we can't extend the array. What can be done here?
Thanks!

The split method that takes one parameter discards trailing empty tokens. Here, this results in params having only a length of one.
User the split method that also takes a limit parameter, and pass a negative limit to ensure that you get an array with a length that matches the number of tokens actually present: 2.
String[] params = splitS1[i].split("=", -1);
Then you won't have to create another array; you'll get an array of size 2 to start with, assuming there is an = present.

The easiest thing would be to test the array length:
String splitS1 = s1.split("\\&");
for (int i = 0; i < splitS1.length; i++) {
String[] params = splitS1[i].split("=");
System.out.println(
"Attribute: " + params[0] +
" Value : " + (params.length < 1 ? "<no value>" : params[1]));
}
It might also be worth using printf instead of println:
System.out.printf("Attribute: %1$s%n Value : %2$s%n",
params[0],
params.length < 1 ? "<no value>" : params[1]
);

Create a class representing a parameter, with its name and value and which parses the string:
public final class Parameter {
private final String name;
private final String value;
public Parameter(String name, String value) {
this.name = name;
this.value = value;
}
public static Parameter parse(String s) {
String[] parts = s.split("=");
String name = parts[0];
String value = "";
if (parts.length > 1) {
value = parts[1];
}
return new Parameter(name, value);
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
// add more behavior if needed.
}
And now you can do
for (int i = 0; i < splitS1.length; i++) {
Parameter param = Parameter.parse(splitS1[i]);
System.out.println("Parameter:" + param.getName() + " = " + param.getValue());
}

Create a new String array and copy the result of split into it.
String[] cpy = new String[2];
for(int i=0;i<cpy.length;i++){
cpy[i] = params[i];
}
params = cpy;

You can do some thing like this
String s1 = "test1=1&test2=2&test3=&test4=4";
String[] splitS1 = s1.split("\\&");
for (int i = 0; i < splitS1.length; i++) {
String[] params = splitS1[i].split("=");
String[] para=new String[2];
if(params.length==1) {
para[0]=params[0];
System.out.println("Attribute:"+para[0]+" Value : "+para [1]);
}
else{
System.out.println("Attribute:"+params[0]+" Value : "+params [1]);
}
}
or
if(params.length==1) {
System.out.println("Attribute:"+para[0]+" Value : "+"");
}
else{
System.out.println("Attribute:"+params[0]+" Value : "+params [1]);
}

Related

How to get first and second character from String in multiple conditions

I have name String[] let suppose "Raj Kumar". Then the condition is that I want to get "R" from Raj and "K" from "Kumar" and if the text is "Raj" then I have to get "Ra" from "Raj". How do I do that below is the code I want to modify.
code:-
public static final String[] titles = new String[]{"Raj", "Niraj Kumar"};
for(int i = 0;i<titles.length;i++){
char firstChar = titles[i].charAt(0);
}
You this method
public String getShortName(String name){
String[] token=name.split(" ");
if(token.length>1){
String value="";
for(int i=0;i<token.length;i++){
value+=token[i].substring(0,1);
}
return value;
}else{
return token[0].length()>1?token[0].substring(0,2):token[0];
}
}
I have tested it, For array of names use this method in for loop
First, create this method to process each individual string in the array:
private static String processString(String string) {
String[] words = string.split(" ");
if (words.length == 1) {
return words[0].substring(0, 2);
} else {
return Arrays.stream(words).map(x -> Character.toString(x.charAt(0))).collect(Collectors.joining());
}
}
And then, stream the array and map each item using the method:
List<String> mapped = Arrays.stream(titles)
.map(YourEnclosingClass::processString)
.collect(Collectors.toList());
You can then print the values out like this:
mapped.forEach(System.out::println);
You can try like this :
public static final String[] titles = new String[]{"Raj", "Niraj Kumar"};
for(int i = 0;i<titles.length;i++){
if(titles[i].contains(" ")){
char firstChar = titles[i].charAt(0) + titles[i].split(" ")[1].charAt(0);
}else{
char firstChar = titles[i].charAt(0) + titles[i].charAt(1);
}
}
final String[] titles = new String[]{"Raj", "Niraj Kumar"};
for (int i = 0;i<titles.length;i++){
String shortChar;
String[] nameSplit = titles[i].split("\\s+");
if(nameSplit.length == 1) {
shortChar = nameSplit[0].substring(0,2);
} else {
shortChar = nameSplit[0].substring(0,1) + nameSplit[1].substring(0,1);
}
}
Here you'll get Ra and NK as output (Hoping that the name contains first and second name only)
Here is another way using stream API:
Arrays.stream(titles)
.map(title -> title.contains(" ") ?
Arrays.stream(title.split(" "))
.reduce("", (a, b) -> a + b.charAt(0)) :
title.substring(0, 2))
.forEach(result -> {
// do with result
});

Issue in looping to parse

I have an xml with 'n' number of data which i am parsing,for test i hardcoded without looping has below,now the below line is just parsing and showing the data for index '1' ,i need to loop this and i am not sure how can i do this.How do i find the length of obj and loop,i cannot find any method in SoapObject.I used like below but the data is getting overridden after parsing
GetReminder getReminder=new GetReminder();
SoapObject obj=(SoapObject)envelope.getResponse();
for(int i=0;i<obj.getPropertyCount();i++) {
KSoap2ResultParser.parseBusinessObject(obj.getProperty(i).toString(), getReminder);}
and the parser is
public static void parseBusinessObject(String input, Object output) throws NumberFormatException, IllegalArgumentException, IllegalAccessException, InstantiationException{
System.out.println("input----> " +input);
Class theClass = output.getClass();
Field[] fields = theClass.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Type type=fields[i].getType();
System.out.println("type--" +type);
fields[i].setAccessible(true);
//detect String
if (fields[i].getType().equals(String.class)) {
String tag = fields[i].getName() + "="; //"s" is for String in the above soap response example + field name for example Name = "sName"
System.out.println("fff------------"+tag);
if(input.contains(tag)){
String strValue = input.substring(input.indexOf(tag)+tag.length(), input.indexOf(";", input.indexOf(tag)));
System.out.println("strvalue------------"+strValue);
if(strValue.length()!=0){
fields[i].set(output, strValue);
}
}
}
//detect int or Integer
if (type.equals(Integer.TYPE) || type.equals(Integer.class)) {
String tag = fields[i].getName() + "="; //"i" is for Integer or int in the above soap response example+ field name for example Goals = "iGoals"
if(input.contains(tag)){
String strValue = input.substring(input.indexOf(tag)+tag.length(), input.indexOf(";", input.indexOf(tag)));
System.out.println("strvalue------------"+strValue);
if(strValue.length()!=0){
fields[i].setInt(output, Integer.valueOf(strValue));
}
}
}
//detect float or Float
if (type.equals(Float.TYPE) || type.equals(Float.class)) {
String tag = "f" + fields[i].getName() + "=";
if(input.contains(tag)){
String strValue = input.substring(input.indexOf(tag)+tag.length(), input.indexOf(";", input.indexOf(tag)));
if(strValue.length()!=0){
fields[i].setFloat(output, Float.valueOf(strValue));
}
}
}
}
You just have to do a for loop on the property count available in the SaopObject.
SoapObject obj=(SoapObject)envelope.getResponse();
int nbProperties = obj.getPropertyCount();
for (int i = 0; i < nbProperties; i++) {
KSoap2ResultParser.parseBusinessObject(obj.getProperty(i).toString(), getReminder);
// Do something with getReminder object
}
Note: if the ouput Object is added to a list for instance, then you should allocate a new ouput object in order for each call to parseBusinessObject() to set the field in a fresh object. E.g.
// Create the list that shall contains the read properties
List<GetReminder> reminders = new ArrayList<>();
SoapObject obj=(SoapObject)envelope.getResponse();
Log.d("Result --ddd- ", obj.toString() );
System.out.println("obj---->" + obj.getPropertyCount());
for(int i=0; i < obj.getPropertyCount(); i++) {
System.out.println("here i is.........." +i);
// Create a new instance
GetReminder rem = new GetReminder();
// Read and set the fields values of rem
KSoap2ResultParser.parseBusinessObject(obj.getProperty(i).toString(), rem);
// Don't forget to store the new reminder in the list
reminders.add(rem);
}
// Do what you want with the list of reminders

Comparing two strings by character in java

I have 2 strings :
first= "BSNLP"
second = "PBN" (or anything that user enters).
Requirement is , O/P should return me the string with only those characters in first but not in second.
Eg. in this case O/P is SL
Eg2.
first = "ASDR"
second = "MRT"
, o/p = "ASD"
For this, the coding I have developed:
String one = "pnlm";
String two ="bsnl";
String fin = "";
for(int i =0; i<one.length();i++)
{
for(int j=0;j<two.length();j++)
{
//System.out.print(" "+two.charAt(j));
if(one.charAt(i) == two.charAt(j))
{
fin+=one.charAt(i);
}
}
}
ch=removeDuplicates(fin);
System.out.print(" Ret ::"+fin);
System.out.println("\n Val ::"+ch);
CH gives me the string with equal characters, but using this logic i cant get the unequal characters.
Can anyone please help?
You can use the Set interface to add all the second array of character so you can check it there later.
sample:
String one = "ASDR";
String two ="MRT";
StringBuilder s = new StringBuilder();
Set<Character> set = new HashSet<>();
for(char c : two.toCharArray())
set.add(c); //add all second string character to set
for(char c : one.toCharArray())
{
if(!set.contains(c)) //check if the character is not one of the character of second string
s.append(c); //append the current character to the pool
}
System.out.println(s);
result:
ASD
I have simple exchange your logic, see:
String one = "pnlm";
String two = "bsnl";
String fin = "";
int cnt;
for (int i = 0; i < one.length(); i++) {
cnt = 0; // zero for no character equal
for (int j = 0; j < two.length(); j++) {
// System.out.print(" "+two.charAt(j));
if (one.charAt(i) == two.charAt(j)) {
cnt = 1; // ont for character equal
}
}
if (cnt == 0) {
fin += one.charAt(i);
}
}
System.out.print(" Ret ::" + fin);
o/p: Ret ::pm.
public static void main(String[] args)
{
String one = "ASDR";
String two ="MRT";
String fin = unique(one, two);
System.out.println(fin);
}
private static String unique(final String one,
final String two)
{
final List<Character> base;
final Set<Character> toRemove;
final StringBuilder remaining;
base = new ArrayList<>(one.length());
toRemove = new HashSet<>();
for(final char c : one.toCharArray())
{
base.add(c);
}
for(final char c : two.toCharArray())
{
toRemove.add(c);
}
base.removeAll(toRemove);
remaining = new StringBuilder(base.size());
for(final char c : base)
{
remaining.append(c);
}
return (remaining.toString());
}
Iterate over the first string
For each character, check if the second string contains it
If it doesn't, add the caracter to a StringBuilder
Return stringBuilder.toString()

how to place the values in get from my loop into an arraylist?

I have this code
for (int i = 0; i < friendslocations.length(); i++)
{
JSONObject c = friendslocations.getJSONObject(i);
String friendName = c.getString(TAG_FRIENDNAME);
System.out.println("friend name " + friendName);
String friendLocation = c.getString(TAG_LOCATION);
System.out.println("friendlocation" + friendLocation);
}
where it keeps printing me the values i want.
But I need to know how to place the values that come out from this loop (the friendname and the friendloaction ) in an array list where each index contains this (friendname, friendlocation).
So how can i do this?
Wrap your two attributes in a new Object and push that object into the arraylist.
class FriendData {
public String friendName;
public String friendLocation
public FriendData(String friendName, String friendLocation) {
this.friendName=friendName;
this.friendLocation=friendLocation;
}
public String toString() {
return "friendName="+friendName+" friendLocation="+friendLocation;
}
}
List<FriendData> friendsList = new ArrayList<>();
for (int i = 0; i < friendslocations.length(); i++) {
JSONObject c = friendslocations.getJSONObject(i);
String friendName = c.getString(TAG_FRIENDNAME);
String friendLocation = c.getString(TAG_LOCATION);
friendsList.add(new FriendData(friendName, friendLocation));
}

Algorithm to search and replace delimited parameters

I have a string that contains multiple parameters delimited by #, like this :
.... #param1# ... #param2# ... #paramN# ...
And I want to replace the parameter placeholders by values.
The current algorithm looks like this:
//retrieve place holder into this SQL select
Pattern p = Pattern.compile(DIMConstants.FILE_LINE_ESCAPE_INDICATOR);
Matcher m = p.matcher(sqlToExec); // get a matcher object
int count = 0;
int start = 0;
int end = 0;
StringBuilder params = new StringBuilder();
while (m.find()) {
count++;
if (count % 2 == 0) {
// Second parameter delimiter
String patternId = sqlToExec.substring(start, m.end());
//Clean value (#value#->value)
String columnName = patternId.substring(1, patternId.length() - 1);
//Look for this column into preLoad row ResultSet and retrieve its value
String preLoadTableValue = DIMFormatUtil.convertToString(sourceRow.get(columnName));
if (!StringUtils.isEmpty(preLoadTableValue)) {
aSQL.append(loadGemaDao.escapeChars(preLoadTableValue).trim());
} else {
aSQL.append(DIMConstants.COL_VALUE_NULL);
}
params.append(" " + columnName + "=" + preLoadTableValue + " ");
end = m.end();
} else {
// First parameter delimiter
start = m.start();
aSQL.append(sqlToExec.substring(end, m.start()));
}
}
if (end < sqlToExec.length()) {
aSQL.append(sqlToExec.substring(end, sqlToExec.length()));
}
I'm looking for a simplest solution, using regexp or another public API. Input parameters will be the source string, a delimiter and a map of values. Output parameter will be the source string with all the parameters replaced.
If this is for a normal SQL query, you might want to look into using PreparedStatements
Beyond that, am I missing something? Why not just use String.replace()? Your code could look like this:
for(int i = 0; i < n; i++){
String paramName = "#param" + i + "#"
sqlToExec = sqlToExec.replace(paramName,values.get(paramName));
}
That assumes you have a map called "values" with string mappings between parameters in the form "#paramN#"
If you need it more generic, this will find and return the whole param including the #'s:
public class ParamFinder {
public static void main(String[] args) {
String foo = "#Field1# #Field2# #Field3#";
Pattern p = Pattern.compile("#.+?#");
Matcher m = p.matcher(foo);
List matchesFound = new ArrayList();
int ndx = 0;
while(m.find(ndx)){
matchesFound.add(m.group());
ndx = m.end();
}
for(Object o : matchesFound){
System.out.println(o);
}
}
}

Categories