Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have started learning Java and have some across some difficulties. I'm trying to subtract two strings.
for example, with these strings;"032"&&"100". I want to be able to subtract each number individually so that the answer would be "032".
I have tried using substring, and parsing the two values to ints, but don't know what to do next. I have also tries using a for loop, to go through each arrays of the strings.
I do not expect for anyone to do this for me, but I would love to get some insight,or to tell me that i'm headed in the right direction
thanks
public static String appliquerCoup( String combinaison, String coup ) {
String nouveauCoup="";
if(combinaison!=null&&coup!=null){
for(int i=0;i>combinaison.length();i++){
int a = Integer.parseInt(combinaison.substring(i, i + 1));
int b = Integer.parseInt(coup.substring(i, i + 1));
nouveauCoup=String.valueOf(a-b);
if(a-b<0){
nouveauCoup=0;
}
}
} // main
return nouveauCoup;
}
If I understand you question correctly. you want to subtract each digit individually.
So (0-1), (3-0), (2-0). The following program does this (yields -132):
public static void main(String[] args) {
String A = "032";
String B = "100";
String str = "";
for(int i = 0; i < A.length(); i++)
{
int a = Integer.parseInt(A.substring(i, i + 1));
int b = Integer.parseInt(B.substring(i, i + 1));
int c = a - b;
str += String.valueOf(c < 0 ? 0 : c);
}
System.out.println(str);
}
Essentially, extract the i-th character of each string, convert them to integers, then do the subtraction. Convert the result back to a string and append it to the result string.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am currently working on a task and I have a question about the Substring method.
For the task I need to get the first Char of a String and delete the first Char after I used it.
The Strings are names and at the end I only want to have "" an empty String left.
My approach:
String name = "Paul";
char chr = name.charAt(0);
String newName = name.substring(1);
My questions: When I am at the last char "l" and use my substring do I get "" or an error?
My questions: When I am at the last char "l" and use my substring do I
get "" or an error?
You will get a blank string. It is also mentioned in the following lines of documentation:
Throws:
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
When you have only l left in the string, its length will be 1 which is perfectly acceptable as the beginIndex. You can also verify it as follows:
public class Main {
public static void main(String[] args) {
System.out.println("l".substring(1));
}
}
To make sure that is error free, do the following.
String name = "Paul";
int nameLength = name.length();
for (int i = 0; i < nameLength; i++){
char chr = name.charAt(0);
if (i != nameLength - 1){
String newName = name.substring(1);
name = newName;
} else {
name = "";
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I understand that I did a lot of hard coding that can be avoided so if anything can share their thought please go ahead:
private String hideEmailCharacters(String privateEmail){
String emailName = privateEmail.substring(0,privateEmail.indexOf("#"));
StringBuilder stringBuffer = new StringBuilder(emailName);
stringBuffer.replace(emailName.length() / 2,emailName.length(), StringUtils.repeat("*", emailName.length() / 2));
String emailProvider = privateEmail.substring(privateEmail.indexOf("#"));
return stringBuffer + emailProvider;
}
The goal is to cover for example half of the email name or cover everything after the second character with stars ** so the result from abcdv#example.com would be ab***#example.com
String processing is cool but here's a solution with Regular Expression.
(?<=.{2}).(?=[^#]*?#)
Intuition:
Ignore first 2 characters from the characters before #
Ignore # as well.
Replace each character between with *
public class TestCode {
private static String hideEmailCharacters(String privateEmail) {
return privateEmail.replaceAll("(?<=.{2}).(?=[^#]*?#)", "*");
}
public static void main(String[] args) {
System.out.println(hideEmailCharacters("abcdv#example.com"));
System.out.println(hideEmailCharacters("ra0o29ajzsdc242#example.com"));
System.out.println(hideEmailCharacters("x2helloyouthere#example.com"));
System.out.println(hideEmailCharacters("a#foo.com"));
}
}
Output:
ab***#example.com
ra*************#example.com
x2*************#example.com
a#foo.com
This piece of code will do the trick:
StringBuffer email = new StringBuffer(privateEmail)
int startIndex = email.indexOf("#")/2;
int endIndex = email.indexOf("#");
int numOfCharsToHide = endIndex - startIndex;
email.replace(startIndex, endIndex, "*".repeat(numOfCharsToHide));
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
For example, string = "ABCDEFGH". if n=2, then output should be "BADCFEHG"; if n=3, output should be "CBAFEDHG".
I know i should use stringbuilder to reverse, but how can i split the string to n parts and then reverse each part?
I will not give you a code for this, you need to learn by trying.
Do this requirement step by step :
how to read that String block by block : String.substring(int, int) in a loop. You need to understand how to calculate the boundery of each blocks
how to reverse a String : see about Reverse a String in JAVA
create the output by mixing those two steps.
Don't try to do everything in once. Find how to do those two separatly, then put the logic together. This is quite simply in the end.
String newStr="";
String oldStr = "ABCDEFGH";
for(int i =0; i<oldStr.length();i+=n) {
if(i+n >= oldStr.length()){
n = oldStr.length()-i;
}
newStr += new StringBuilder(oldStr.substring(i,i+n)).reverse().toString();
}
Edit: Sorry for missreading your question, this little loop does what you're asking for!
What we are doing here is making oldString.length() / n iterations to split the String in n portions. Because the length might not be dividable by your n we have to check if i+n wont be larger than the length of your word (eventually creating a IndexOutOfBoundsException). If this is the case we just set n so that it adds to i to the rest of the word. Hope that explains it well.
I've given you most of the code but it's unfinished. You will have to understand what I left out and how to fix it to complete the problem.
String originalString = someString; //String from user
String tempString = ""; //String used for temporary reasons
String finalString = ""; //Your end result
int n = someNumber; //Number from user
//Loops through the original string, incrementing by n each time
for (int i = 0; i < originalString.length() - n; i += n)
{
//Gives us the current substring to reverse
tempString = originalString.substring(i, i + n);
//Starts at end of substring and adds each char to the final string
for (j = n - 1; j >= 0; j--)
{
finalString += tempString.charAt(j);
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have been attempting to use a quadratic sort in java, to sort an arraylist of messages.
I have used the following code, however it will not compile for me. The error I keep getting is
cannot find symbol variable length
Below is the sort and the swap I am using:
public static void quadraticSort(ArrayList<Message> m)
{
String s1 = "abcd";
String s2 = "efgh";
int val = "abcd".compareTo("efgh");
for (int i = 0; i < s1.length; i += 1)
{
for (int s2 = i; s2 < s1.length; s2 += 1)
{
if ((int)s1[s2].messageText.compareTo(0) <(int)s2[i].messageText.compareTo(0))
{
swap(s1, i, s2);
}
}
}
}
private static void swap(ArrayList<Message> list, int to, int from)
{
Message temp = list[to];
list.set(to , from);
list.set(from , temp);
}
In your code you're trying to access a length property/field of your String instances, which does not exist. Instead, you want to use the length() method:
String s = "abc";
s.length(); // = 3
s.length; // compiler error
But you have more bugs than that. You're also attempting to access an indexed value of your String using array/bracket notation:
s1[s2]
The characters of String objects are not accessible in this manner. You should use the charAt() method instead.
I suggest you read the javadoc for String. In Java they are treated as first class objects; not an array of characters.
To get the length of a string, you must use length(). Additionally, to get a character from a given position in the String, you must use charAt(int index)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
How to create an array from a string with two respective data items.
String str="USA*2*Japan*8^2*India*5^4^2*Germany*5*";
Here, I want to create an array of two items in .
Like this:
Arraylist<string> arr= [USA*2,Japan*8^2, India*5^4^2,Germany*5];
Here * is indicating main items and ^ is indicating sub items.
You are using the * to separate "main items" but it can also be inside the main item.
Your requirements look odd, but lets assume for the sake of argument that you are getting your input data like this and you want to split it like you suggested.
That means that every * that is preceded by a number is a separator, but a * that is not preceded by a number is not.
You can achieve that using regular expressions: (with a positive look-behind expression (?<=expr)
String str = "USA*2*Japan*8^2*India*5^4^2*Germany*5";
List<String> lst = Arrays.asList(Pattern.compile("(?<=\\d)\\*").split(str));
System.out.println(lst);
Prints:
[USA*2, Japan*8^2, India*5^4^2, Germany*5]
After further clarification in the comment below, it seems that the problem is more generic than the initial example; the question becomes:
How do I split a string on a separator, but only after 2 occurrences
of the separator.
Although it's possible to do with a regex, it may be easier to do and understand in a for loop like this:
public static List<String> split(String str, char splitChar, int afterOccurrences) {
List<String> lst = new ArrayList<>();
int occurrencesSeen = 0;
int start = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == splitChar) {
occurrencesSeen++;
if (occurrencesSeen >= afterOccurrences) {
lst.add(str.substring(start, i));
start = i + 1;
occurrencesSeen = 0;
}
}
}
if (start < str.length() - 1)
lst.add(str.substring(start));
return lst;
}
public static void main(String[] args) {
String str = "USA*2*Japan*8^2*India*5^4^2*Germany*5";
System.out.println(split(str, '*', 2));
}
This method also allows you to split after 3 or any other number of occurrences.