I have two problem. Please try to solve...
No 1.
Suppose I have two string:-
String one = "Android is awesome";
String two = "Android is";
Now my question is, can I get awesome by comparing those two string like we do with int.
int abc = 50;
int def = 35;
int ghi = abc - def;
output :-
ghi = 15;
So, this is what we do basically with int, long, double... Is it possible also with String?
No 2.
Now, suppose again I have a string-array
ArrayList<String> list = new Arraylist()<>;
list.add("beautiful");
list.add("awesome");
list.add("cool");
Now, if string-comparing is possible, then suppose I have got a new String three from comparing one and two.
So, here,
String three = "awesome";
Now, again, I am using if-statement
if(list.contains("awesome")){
**Problem here starts. See the commented texts**
//Here if **awesome** is found in **list**, so can I get the position of **awesome** in the **list**?
}
Forgive me for a big and rough question. Please help me. I am really so sad with this problem.
If you want the remaining string by comparing two strings, try the following
String one = "Android is awesome";
String two = "Android is";
if(one.contains(two)){
Log.i("remaining string ",one.split(two)[0].replace(" ",""));
Log.i("remaining string ",one.split(two)[1].replace(" ",""));
}else{
Log.i("remaining string ","");
}
Then use the remaining string to find the index from list.Try the following ,
list.indexOf(remainingstring);
Related
I have an api which returns a String in the following format:
ACTNEW_38_0001,ACTO_57999
I need to extract the numerical values (57999, or 38_0001) but:
1: They can arrive in different order.
2: It can arrive only one of them.
3: It has to be lightweight.
I roughly know how to do it. My actual code looks more or less like this:
private final String tipoActivity = "ACTO_";
private String obtenerSplitOldElem(String toSplit) {
if(toSplit.contains(",")) {
String[] split = toSplit.split(",");
int element = ArrayUtils.indexOf(toSplit, "ACTO_");
String split2[] = split[element-1];
return split2[1];
} else {
String[] split = split.split("ACTO_");
return split[1];
}
return "";
}
The thing is that:
1: I think there should be a better way to achieve this.
2: I haven´t tried yet the arrayUtils.indexOf. If it doesn´t work I would have to do a contains, probably inside a for loop, but I think it´s a bad idea for something so simple.
Any help would be appreciated. Thanks
You could use a regex find all approach on your CSV string:
String input = "ACTNEW_38_0001,ACTO_57999";
List<String> nums = Pattern.compile("\\d+(?:_\\d+)*")
.matcher(input)
.results()
.map(MatchResult::group)
.collect(Collectors.toList());
System.out.println(nums); // [38_0001, 57999]
Hello im a total beginner in Java and have a problem. In a code below that has an array of fixed list of guests, how can i print emails of these person? The email must consist of 3 first name digits and two first surname digits, and after these are #guest.com. So it looks like this:
adaro#guest.com
thost#guest.com
In this task i must use methods: substring, split, toLowerCase.
Sorry for my english its not perfect. Please help i've tried to solve this but i'm stuck cant manage it.
public class email {
public static void main(String[] args) {
String[] guests = { "Rock Adam",
"Stewart Thomas",
"Anderson Michael",
};
}
}
When you are stuck like this, try breaking down the problem bit by bit.
You are saying you don't know how to extract part of string, but also how to print. I'm tempted to give you written instructions and not the full answer to your question because that's how you will learn better.
You need to construct this email for each String in the String[] array. Look for iterating over arrays in java here for example https://www.geeksforgeeks.org/iterating-arrays-java/
For each String which is of this form "Rock Adam" you need to extract the surname and last name. To do this you need to split the String by space " ". How to do that - How to split a String by space
When you split by space you will get another Array of two elements, first will be surname, second will be first name. Use array indecies to access them.
When you access the firstName your next problem is - how do I get the first 3 characters of that String. How to access 3rd or 2nd is the same problem see how to do this here Extract first two characters of a String in Java
Now that you have the substrings you want to know how to concatenate and print them. How to print multiple variables? Answer is here How to print multiple variable lines in Java. Also for transforming the strings to lowercase you can find answer here https://www.w3schools.com/java/ref_string_tolowercase.asp
Try to do some more work yourself following this and you will learn much more than from copy-pasting what someone will give you directly for free.
Lower code solves your problem. String.split(" ") splits the String at the first occurrence of blank space. It gives a String array back which contains both parts of the name. With String.substring() you can get specific parts of the String.
public static void main(String[] args) {
String[] guests = {"Rock Adam",
"Stewart Thomas",
"Anderson Michael"};
for(String guest : guests){
String[] name = guest.split(" ");
String email = name[1].substring(0,3).toLowerCase() + name[0].substring(0,2).toLowerCase() + "#guest.com";
System.out.println(email);
}
}
Below code is exactly what you are looking for (i guess)
String[] guests = { "Rock Adam",
"Stewart Thomas",
"Anderson Michael",
};
List<String> emailIdList = new ArrayList<>();
for (String guest : guests) {
String firstName = guest.split(" ")[1];
String lastName = guest.split(" ")[0];
String emailId = firstName.substring(0,2) + lastName.substring(0,1) + "#guest.com";
emailIdList.add(emailId);
}
I have an array in my modularized program and i am trying to find the amount of times Strings appear in the array. I cannot post my code as it violates my schools honor code, just looking some help....I cannot use any classes besides JOptionPane. Java code.
i am not sure cause you dont post your code but i know you want that :
String[] yourArray = {"test", "1234","test"};
String yourStringTest = "test";
int occurence = 0;
for(int i = 0; i < yourArray.length;i++) {
if(yourStringTest.equalsIgnoreCase(yourArray[i])) {
occurence++;
}
}
System.out.println("the string "+yourStringTest+" appear :"+occurence);
For example I have a String like this:
String myString = "Money = 10
Arrows = 4"
I want to edit the arrows, so I have to find the word "Arrow" in the String and edit the number "4". Any idea how to do that?
Thanks!
If you want to edit a value easily based on something else in the program, you can make it so the number is a variable instead. Judging by the code as well, you want there to be a new line, currently it's not doing that since you need to use "\n"
So the code should look like:
int arrows = 4;
String myString = "Money = 10" + "\n" + "Arrows = " + arrows;
If you then change the value of the integer arrows before declaring the string it will be different.
I don't use java that much but if you need to find out is something is a letter you can use
System.out.println(Character.isLetter('c'));
System.out.println(Character.isLetter('5'));
And since your data is in a string you can loop trough it like trough an array, as far as I remember.
for(int i =0; i < yourStringName.length; i++)
But I must agree with #jack jay.
So here is a helpful post Java associative-array
So in Java, I know that str.endsWith(suffix) tests if str ends with something. Let's say I have a text with the line "You are old" in it. How would I take the "old" and set it as a variable so I can print it out in the console?
I know I could do:
if(str.endsWith("old")){
String age = "old";
}
But then I'm going to have more options, so then I'd have to do:
if(str.endsWith("option1")){
String age = "option1";
}
if(str.endsWith("option2")){
String age = "option2";
}
...
Is there a more efficient and less verbose way to check the end of strings over writing many, possibly hundreds, of if statements
Format:
setting: option
setting2: option2
setting3: option3 ...
Regardless of what "option" is, I want to set it to a variable.
If you are working with sentences and you want to get the word, do
String word = str.substring(str.lastIndexOf(" "));
You may need a +1 after the lastIndexOf() to leave the space out.
Is that what you are looking for?
Open your file and read the line with the readLine() method. Then to get the last word of the string you can do as it is suggested here
You mean like:
String phrase = "old";
if(str.endsWith(old)){
Is this what you're looking for?
List<String> suffixes = new ArrayList<String>();
suffixes.add("old");
suffixes.add("young");
for(String s: suffixes)
{
if (str.endsWith(s))
{
String age = s;
// .... more of your code here...
}
}
If you're worried about repeating very similar code, the answer is always (99%) to create a function,
So in your case, you could do the following:
public void myNewFunction(String this, String that){
if(this.endsWith(that)){
String this = that;
}
}
...
String str = "age: old";
myNewFunction(str, "old"); //Will change str
myNewFunction(str, "new"); //Will NOT change str
And if that is too much, you can create a class which will do all of this for you. Inside the class, you can keep track of a list of keywords. Then, create a method which will compare a given word with each keyword. That way, you can call the same function on a number of strings, with no additional parameters.
You could use this Java code to solve your problem:
String suffix = "old";
if(str.endsWith(suffix)) {
System.out.println(suffix);
}