Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Reversing the string while maintaining the index of COMMA.
the string that need to be reversed : "T,he ,quick, bro,wn f,ox jump,s over, the l,azy do,g".
Expected output: "g,od ,yzal ,eht ,revo, spmuj ,xof nw,orb kc,iuq eh,T"
use StringBuffer and Stack first remove all commas and save the index of them on stack after reversing insert commas at location that you saved them on stack. use stringBufferObject.deleteCharAt(index); for deleting a character and use stringBufferObject.reverse(); for reversing string.
Here is the code with your input
public class Test {
public static void main(String [] args){
String original = "T,he ,quick, bro,wn f,ox jump,s over, the l,azy do,g";
String reverse = "";
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: "+reverse);
}
}
Here this is code you can use it
String original = "T,he ,quick, bro,wn f,ox jump,s over, the l,azy do,g";
String reverse = original.replaceAll(",","");
StringBuilder rev = new StringBuilder(reverse);
rev = rev.reverse();
String output="";
int j = 0;
for (int i = 0; i < original.length(); i++) {
if(original.charAt(i) == ','){
output += ",";
}else{
output+=rev.charAt(j++);
}
}
System.out.println(output);
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 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 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.
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
please help me find the code for getting the next character in the string
for example:
input string = "abcd"
output string = "bcde"
I can able to iterate only one character at the time.
thanks in advance
Get the ASCII of the last character in the String and increase the ASCII value by 1.
try this,
String sample = "abcd";
int value = (int) sample.charAt(sample.length() - 1); // here you get the ASCII value
System.out.println("" +((value < ((int)'z')) ? sample.substring(1) + (char) (value + 1) : sample));
Simply add one to the char values:
char[] chars = "abcd".toCharArray();
for (int i = 0; i < chars.length; i++) {
chars[i] += 1;
}
String nextChars = new String(chars);