I have an array with several elements String[] names = {"Jeremy", "Aude", "David"};
I would like to use the method .substring() to extract the index 1 and 2 namely the elements Aude and David then I want to concatenate the element Jeremy also.
Here is the result that I want to get : Aude, David, Jeremy
Do you have an idea to manipualte the elements ?
Here is my code
ArrayList<String> myList = new ArrayList<>();
String[] names = {"Jeremy", "Aude", "David"};
String x = "";
for(int i = 0; i<names.length; i++){
myList.add(names[i]);
System.out.print(myList.get(i) + " ");
}
x = names.substring(1,2);
You could do it pretty much as described, first create a new array of the same length as names (since you want to keep all of the names, just rotate them). Next, copy every name with an offset of one from names to that second array. Finally, copy the first name to the last element in the second array (and print it). Like,
String[] names = { "Jeremy", "Aude", "David" };
String[] names2 = new String[names.length];
System.arraycopy(names, 1, names2, 0, names.length - 1);
names2[names2.length - 1] = names[0];
System.out.println(Arrays.toString(names2));
Outputs (as requested)
[Aude, David, Jeremy]
extract the index 1 and 2
names[1] and names[2]
element Jeremy also
names[0]
concatenate ... result that I want to get: Aude, David, Jeremy
String result = names[1] + ", " + names[2] + ", " + names[0];
would like to use the method .substring()
You can't, since that method is not for array manipulation.
Code
String[] names = {"Jeremy", "Aude", "David"};
String result = names[1] + ", " + names[2] + ", " + names[0];
System.out.println(result);
Output
Aude, David, Jeremy
I would not use .substring() to access the elements in an array. you can use their location in memory by getting them by their index.
ArrayList<String> myList = new ArrayList<>();
String[] names = {"Jeremy", "Aude", "David"};
String x = "";
for(int i = 0; i<names.length; i++){
myList.add(names[i]);
System.out.print(myList.get(i) + " ");
}
x = names[1] + ", " names[2] + ", " names[0];
.substring() is used to get elements in an String such as
`String x = "jeremy;
x = x.substring(0, 2);`
x will now equal to "jer"
I would also advise to use StringBuilder as it is mutable
The variable 'String [] names' is not an object of String but rather an object of the generic container class array, containing the object type String. This means that the method that you are trying to access is not usable due to being an array. You will have to make a new function that takes in the 2 parameters and returns a String.
public String subString(int index1,int index2)
{
if(names.length < index1 || names.length < index2)
{
return names[index1] + ", " + names[index2];
}
return "Index's not in array range";
}
Related
I have a string bac/xaz/wed/rgc. I want to get the substring before and after the middle / in the string.
I don't find the solution with string split. how to achieve this? I am not sure if I have to use regex and split the string.
public static void main(String ...args) {
String value = "bac/xaz/wed/rgc/wed/rgc";
// Store all indexes in a list
List<Integer> indexList = new ArrayList<>();
for (int i = 0; i < value.length(); i++) {
if (value.charAt(i) == '/') {
indexList.add(i);
}
}
// Get the middle index from the list, works for odd number only.
int middleIndex = indexList.get(indexList.size() / 2);
System.out.println("First half: " + value.substring(0, middleIndex));
System.out.println("Second half: " + value.substring(middleIndex + 1));
}
Not an elegant solution, but it can handle as much '/' you gave it, as long as the total number of '/' is odd number.
Using an ArrayList might be overkill, but it works XD.
You can use split function to achieve that, using / as a delimiter:
String str = "bac/xaz/wed/rgc";
String[] arr = str.split('/');
You'll get an array of 4 strings: ["bac", "xaz", "wed", "rgc"].
From then on, you can retrieve the one that you want. If I understand well, you are interested in the elements 1 and 2:
String before = arr[1];
String after = arr[2];
If you meant to get the whole sub-string before the middle /, you can still concatenate the first two strings:
String strbefore = arr[0] + arr[1];
Same goes for the rest:
String strafter = arr[2] + arr[3];
here is a simple solution
String str = "bac/xaz/wed/rgc";
int loc = str.indexOf("/",str.indexOf('/')+1);
String str1 = str.substring(0,loc);
String str2 = str.substring(loc+1,str.length());
System.out.println(str1);
System.out.println(str2);
bac/xaz
wed/rgc
I need to get all the index numbers were in i will get a match of the keyword 'Articles' & also i want the counter 'indexoccurencecounter' to increment only if i get a match.
List<String> valueslist = new ArrayList<String>();
valueslist.add("Articles");
valueslist.add("Vals");
valueslist.add("Articles");
valueslist.add("Toast");
String key="Articles";
System.out.println("List contents having values are: "+valueslist);
int ind=0;
int indexoccurencecounter=0;
for (int i=0;i<valueslist.size();i++){
ind=valueslist.indexOf(key);
if (ind>=0){
indexoccurencecounter++;
}
}
System.out.println("Index's of the key "+key+" is: "+ind);
System.out.println("The key specified appears "+indexoccurencecounter+" times in the result links");
My above code is giving me incorrect output, i am expecting the output to be like below:
List contents having values are: [Articles, Vals, Articles, Toast]
Index's of the key Articles is: 0,2
The key specified appears 2 times in the result links
Because multiple indexes will match, int ind cannot keep track of them all. It could only keep track of one. I suggest you create a List<Integer> of indices. A useful side-effect of doing that is that you no longer have to count the occurrences—you can simply use the size() method of the list.
List<String> values = new ArrayList<>();
values.add("Articles");
values.add("Vals");
values.add("Articles");
values.add("Toast");
String searchTerm = "Articles";
List<Integer> matchingIndices = new ArrayList<>();
for (int i = 0; i < values.size(); i++) {
String candidate = values.get(i);
if (candidate.indexOf(searchTerm) >= 0) {
matchingIndices.add(i);
}
}
int numberOfMatches = matchingIndices.size();
System.out.println("Values: " + values);
System.out.println("Indexes of the key '" + searchTerm + "': " + matchingIndices);
System.out.println("The key appears " + numberOfMatches + " times.");
Produces:
Values: [Articles, Vals, Articles, Toast]
Indexes of the key 'Articles': [0, 2]
The key appears 2 times.
String Qty1 = "1";
String Qty2 = "2";
String qtyString = "", bString = "", cString = "";
for(int j = 1; j <= 2; j++)
{
qtyString = String.valueOf(("Qty" + j));
System.out.println("qtyString = " + qtyString);
}
output:
qtyString = Qty1;
qtyString = Qty2;
I would like to get qtyString = 1, qtyString = 2; I want to print Qty1 and Qty2 value in my for loop. In C#, this code works correctly. I don't know how to get qtyString value as 1, 2 in java.
You should use array of strings for this purpose.
String[] Qty = {"1","2"};
for(int j = 0 ; j < 2 ;j++)
{
System.out.println("qtyString = " + Qty[j]);
}
String array is needed if you want to print a list of string:
String[] Qty = {"1", "2"};
String qtyString = null;
for (int j = 0; i<=1; j++) {
qtyString = Qty[j];
System.out.println("qtyString = " + qtyString);
}
output:
qtyString = 1
qtyString = 2
I don't know for sure what you're trying to do, and you've declared Qty1 twice in your code. Assuming the second one is supposed to be Qty2, then it looks like you're trying to use string operations to construct a variable name, and get the value of the variable that way.
You cannot do that in Java. I'm not a C# expert, but I don't think you can do it in C# either (whatever you did that made you say "it works in C#" was most certainly something very different). In both those languages and in all other compiled languages, the compiler has to know, at compile time, what variable you're trying to access. You can't do it at runtime. (Technically, in Java and C#, there are ways to do it using reflection, depending on how and where your variables are declared. But you do not want to solve your problem that way.)
You'll need to learn about maps. Instead of separate variables, declare a Map<String, String> that maps the name that you want to associate with a value (Qty1, Qty2) with the value (which is also a String in this case, but could be anything else). See this tutorial for more information. Your code will look something like
Map<String, String> values = new HashMap<>();
values.put("Qty1", "1");
values.put("Qty2", "2");
...
qtyString = values.get("Qty"+j);
(Actually, since your variable name is based on an integer, an array or ArrayList would work perfectly well too. Using maps is a more general solution that works in other cases where you want names based on something else beside sequential integers.)
Try this examples:
With enhanced for-loop and inline array:
for(String qty : new String[]{"1", "2"})
System.out.printf("qtyString = %s\n", qty);
With enhanced for-loop and array:
String [] qtys = {"1", "2"};
for(String qty : qtys)
System.out.printf("qtyString = %s\n", qty);
Using for-loop and array:
String [] qty = {"1", "2"};
for(int i = 0; qty.length > i; i ++)
System.out.printf("qtyString = %s\n", qty[i]);
you can try this for java:
static String Qty[] = {"1", "2"} ;
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int j = 0 ; j < 2 ;j++)
{
System.out.println("qtyString = " + Qty[j]);
}
}
And For Android:
String[] Qty = {"1","2"};
for(int j = 0 ; j < 2 ;j++)
{
System.out.println("qtyString = " + Qty[j]);
}
I am trying to make an Array that starts at an initial size, can have entries added to it. (I have to use an Array). To print the Array I have to following code :
public String printDirectory() {
int x = 0;
String print = String.format("%-15s" + "%-15s" + "%4s" + "\n", "Surname" , "Initials" , "Number");
// Sorts the array into alphabetical order
// Arrays.sort(Array);
while ( x < count ){
Scanner sc = new Scanner(Array[x]).useDelimiter("\\t");
secondName[x] = sc.next();
initials[x] = sc.next();
extension[x] = sc.next();
x++;
}
x = 0;
while ( x < count){
print += String.format("%-15s" + "%-15s" + "%4S" + "\n", secondName[x] , initials[x] , extension[x]);
x++;
}
return print + "" + Array.length;
}
Please ignore the extra Array.length, on the return statement.
Anyways this is working fine, firstly the Array reads a file which is formated like NameInitialsnumber on each line.
So I tried making a newEntry method and it causes problems when I want to print the Array. When I add a new entry, if the Array is too small, it will make the array bigger and add the entry. I made methods to make sure this worked and it does work. The following code for this method is:
public void newEntry(String surname, String in, String ext) {
if (count == Array.length) {
String entry = surname + "\t" + in + "\t" + ext;
int x = Array.length + 1;
String[] tempArray = new String[x];
System.arraycopy(Array, 0, tempArray, 0, Array.length);
Array = tempArray;
Array[count] = entry;
Arrays.sort(Array);
} else {
String entry = surname + "\t" + in + "\t" + ext;
Array[count] = entry;
Arrays.sort(Array);
}
count++;
}
The problem is when I then call the printDirectory method it has problems with sc.next(). The error message is as follows:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at ArrayDirectory.printDirectory(ArrayDirectory.java:106)
at ArrayDirectory.main(ArrayDirectory.java:165)
Im really new to coding and im not sure what is wrong. I know its something wrong with the new entry but im not sure what. Really grateful for any help. Thanks.
It seems that your other arrays secondName, initials, and extension are not large enough.
You need to make them bigger as well. Or even better, when you think a bit about it you will recognize that you do not need them at all.
I believe the regex would be "[A-Z]{2} [0-9]{5}". How would I go through the list and add a comma between the two? Between the state abbreviation and the zip code.
Should I find where the regex is and then just add a comma at index 2?
Assuming the list of strings always has an abbreviation and a post code at the end of each string, you can loop through the list and call this, using the return value to replace the existing string.
public String addComma(String address) {
String[] tmp = address.split(" ");
String newAddress = "";
int len = tmp.length;
for (int i = 0; i < len - 2; i++) {
//add all the information before the state abbreviation and post code
newAddress = newAddress + tmp[i] + " ";
}
return (newAddress + tmp[len - 2] + ", " + tmp[len - 1]);
}