I have written this code to find the possible permutation of string using iterative approach, but it's giving wrong output as follows. Please advise, what's wrong in the code?
Output I'm getting:
BCAABC ACBABC ABCABC
Expetced output is :
ABC ACB BAC BCA CBA CAB
public class PrintPermutation {
public static void main(String[] args) throws Exception {
String str = "ABC";
String permutation = str + "";
if (str.length() == 0) {
System.out.println("String length is zero and can't make the permutation");
return;
}
for (int i = 0; i < str.length(); i++)
{
char ch = str.charAt(i);
String left = str.substring(0, i);
String right = str.substring(i + 1);
String Merge = left + right;
System.out.println(Merge+ch+permutation);
}
}
}
This is a solution I found online. This one is interesting, because rather than using recursion or some complex iterative algorithm, they make the solution simpler by using some mathematical understanding. link here
public static void permutateString2(String s){
int len = s.length();
int factorial = factorial(s.length());
for (int i=0; i<factorial; i++){
String str = s;
int counter = 0;
StringBuilder permutation = new StringBuilder();
while (counter < len){
int idx = i % (len - counter);
permutation.append(str.charAt(idx));
if (idx == 0){
str = str.substring(idx+1);
}else if (idx == str.length()-1){
str = str.substring(0, str.length()-1);
}else{
str = str.substring(0, idx) + str.substring(idx+1, str.length());
}
counter++;
}
System.out.println(permutation.toString());
}
}
private static int factorial(int n){
int result = 1;
for (int i=1; i<= n; i++){
result *= i;
}
return result;
}
What my codes does is pass two string and a count in the method countSubstring.
countSubString count the occurances of strTwo in strOne.
But I am have difficulty because I don't understand a few things:
public class CountingSubString
{
int CountSubString(String strOne, String strTwo, int count)
{
int i = 0;
int foundAtIndex = strOne.indexOf(strTwo, i);
if(foundAtIndex == -1)
{
i++;
}
else//(foundAtIndex != -1)
{
count++;
int newStartIndex = foundAtIndex + strTwo.length();
String StringFromString = strOne.substring(newStartIndex, strOne.length()-1);
count = count + countSubString(StringFromString, strTwo, count);
return count;
}
return count;
}
public class TestCountingSubString
{
public static void main(String[] argv)
{
String s2 = new String("abab");
String s3 = new String("ab");
String s4 = new String("aabbaa");
String s5 = new String("aa");
countingSubString CountOfString = new countingSubString();
int count = CountOfString.countSubString(s2, s3, 0);
System.out.println(count);
}
}
Question 1) let consider a case where string1 = c, and string2 = aa.
aa is not contained in c.
How do I make a base case for this case?
My attempt:
Question 2) In java how does a string end?
If I have string1 = "aabbaa", and string2 = "aa".
I get aa from index 0 and 1, so I return index 0. compute string2.length() + 0 = 2.
Now I substring string 1 at beginIndex: 2 to endindex: string2.length-1 to get new string to obtain "bbaa".
Searching again, I obtain string aa at index 2 and 3.
How do I make my recursive end after the string aa?
Why are you complicating things. It's java, use its features.
String string1 = "abab";
Pattern p = Pattern.compile("ab");
Matcher m = p.matcher(string1);
int count = 0;
while (m.find()){
count +=1;
}
System.out.println(count);
Also for your understanding, substring function has following format
public String substring(int beginIndex, int endIndex)
where
beginIndex -- the begin index, inclusive.
endIndex -- the end index, exclusive.
Safety condition as asked in Question 1
if (strOne == null || strOne.equals("") || strTwo.length() < sub.length())
return 0;
Solution to Question 2
int index = strOne.indexOf(strTwo);
if(index!=-1){
count++;
count+= countSubString(strOne.substring(index+1),strTwo,0);
}
So complete solution is
class countingSubString
{
int countSubString(String strOne, String strTwo, int count)
{
if (strOne == null || strOne.equals("") || strOne.length() < strTwo.length())
return 0;
int index = strOne.indexOf(strTwo);
if(index!=-1){
count++;
count+= countSubString(strOne.substring(index+1),strTwo,0);
}
return count;
}
}
Also remove public modifier from class countingSubString as there can be only one public class in one file. And also follow naming convention so class name should be
CountingSubString instead of countingSubString
You can use a recursive function as follows. I modified the class and function names a little bit.
You don't need to pass 'count' parameter to countSub function, since it will be eventually returned recursively.
public class Count
{
public static void main(String[] argv) {
String s2 = new String("ababab");
String s3 = new String("ab");
String s4 = new String("aabbaa");
String s5 = new String("aa");
int count = countSub(s2, s3);
System.out.println(count);
}
public static int countSub(String strOne, String strTwo) {
int foundAtIndex = strOne.indexOf(strTwo);
if(foundAtIndex == -1) {
return 0;
} else {
int newStartIndex = foundAtIndex + strTwo.length();
String newString = strOne.substring(newStartIndex, strOne.length());
return (1 + countSub(newString, strTwo));
}
}
}
For accessing individual characters of a String in Java, we have String.charAt(2). Is there any inbuilt function to remove an individual character of a String in java?
Something like this:
if(String.charAt(1) == String.charAt(2){
//I want to remove the individual character at index 2.
}
You can also use the StringBuilder class which is mutable.
StringBuilder sb = new StringBuilder(inputString);
It has the method deleteCharAt(), along with many other mutator methods.
Just delete the characters that you need to delete and then get the result as follows:
String resultString = sb.toString();
This avoids creation of unnecessary string objects.
You can use Java String method called replace, which will replace all characters matching the first parameter with the second parameter:
String a = "Cool";
a = a.replace("o","");
One possibility:
String result = str.substring(0, index) + str.substring(index+1);
Note that the result is a new String (as well as two intermediate String objects), because Strings in Java are immutable.
No, because Strings in Java are immutable. You'll have to create a new string removing the character you don't want.
For replacing a single char c at index position idx in string str, do something like this, and remember that a new string will be created:
String newstr = str.substring(0, idx) + str.substring(idx + 1);
String str = "M1y java8 Progr5am";
deleteCharAt()
StringBuilder build = new StringBuilder(str);
System.out.println("Pre Builder : " + build);
build.deleteCharAt(1); // Shift the positions front.
build.deleteCharAt(8-1);
build.deleteCharAt(15-2);
System.out.println("Post Builder : " + build);
replace()
StringBuffer buffer = new StringBuffer(str);
buffer.replace(1, 2, ""); // Shift the positions front.
buffer.replace(7, 8, "");
buffer.replace(13, 14, "");
System.out.println("Buffer : "+buffer);
char[]
char[] c = str.toCharArray();
String new_Str = "";
for (int i = 0; i < c.length; i++) {
if (!(i == 1 || i == 8 || i == 15))
new_Str += c[i];
}
System.out.println("Char Array : "+new_Str);
To modify Strings, read about StringBuilder because it is mutable except for immutable String. Different operations can be found here https://docs.oracle.com/javase/tutorial/java/data/buffers.html. The code snippet below creates a StringBuilder and then append the given String and then delete the first character from the String and then convert it back from StringBuilder to a String.
StringBuilder sb = new StringBuilder();
sb.append(str);
sb.deleteCharAt(0);
str = sb.toString();
Consider the following code:
public String removeChar(String str, Integer n) {
String front = str.substring(0, n);
String back = str.substring(n+1, str.length());
return front + back;
}
You may also use the (huge) regexp machine.
inputString = inputString.replaceFirst("(?s)(.{2}).(.*)", "$1$2");
"(?s)" - tells regexp to handle newlines like normal characters (just in case).
"(.{2})" - group $1 collecting exactly 2 characters
"." - any character at index 2 (to be squeezed out).
"(.*)" - group $2 which collects the rest of the inputString.
"$1$2" - putting group $1 and group $2 together.
If you want to remove a char from a String str at a specific int index:
public static String removeCharAt(String str, int index) {
// The part of the String before the index:
String str1 = str.substring(0,index);
// The part of the String after the index:
String str2 = str.substring(index+1,str.length());
// These two parts together gives the String without the specified index
return str1+str2;
}
By the using replace method we can change single character of string.
string= string.replace("*", "");
Use replaceFirst function of String class. There are so many variants of replace function that you can use.
If you need some logical control over character removal, use this
String string = "sdsdsd";
char[] arr = string.toCharArray();
// Run loop or whatever you need
String ss = new String(arr);
If you don't need any such control, you can use what Oscar orBhesh mentioned. They are spot on.
Easiest way to remove a char from string
String str="welcome";
str=str.replaceFirst(String.valueOf(str.charAt(2)),"");//'l' will replace with ""
System.out.println(str);//output: wecome
public class RemoveCharFromString {
public static void main(String[] args) {
String output = remove("Hello", 'l');
System.out.println(output);
}
private static String remove(String input, char c) {
if (input == null || input.length() <= 1)
return input;
char[] inputArray = input.toCharArray();
char[] outputArray = new char[inputArray.length];
int outputArrayIndex = 0;
for (int i = 0; i < inputArray.length; i++) {
char p = inputArray[i];
if (p != c) {
outputArray[outputArrayIndex] = p;
outputArrayIndex++;
}
}
return new String(outputArray, 0, outputArrayIndex);
}
}
In most use-cases using StringBuilder or substring is a good approach (as already answered). However, for performance critical code, this might be a good alternative.
/**
* Delete a single character from index position 'start' from the 'target' String.
*
* ````
* deleteAt("ABC", 0) -> "BC"
* deleteAt("ABC", 1) -> "B"
* deleteAt("ABC", 2) -> "C"
* ````
*/
public static String deleteAt(final String target, final int start) {
return deleteAt(target, start, start + 1);
}
/**
* Delete the characters from index position 'start' to 'end' from the 'target' String.
*
* ````
* deleteAt("ABC", 0, 1) -> "BC"
* deleteAt("ABC", 0, 2) -> "C"
* deleteAt("ABC", 1, 3) -> "A"
* ````
*/
public static String deleteAt(final String target, final int start, int end) {
final int targetLen = target.length();
if (start < 0) {
throw new IllegalArgumentException("start=" + start);
}
if (end > targetLen || end < start) {
throw new IllegalArgumentException("end=" + end);
}
if (start == 0) {
return end == targetLen ? "" : target.substring(end);
} else if (end == targetLen) {
return target.substring(0, start);
}
final char[] buffer = new char[targetLen - end + start];
target.getChars(0, start, buffer, 0);
target.getChars(end, targetLen, buffer, start);
return new String(buffer);
}
*You can delete string value use the StringBuilder and deletecharAt.
String s1 = "aabc";
StringBuilder sb = new StringBuilder(s1);
for(int i=0;i<sb.length();i++)
{
char temp = sb.charAt(0);
if(sb.indexOf(temp+"")!=1)
{
sb.deleteCharAt(sb.indexOf(temp+""));
}
}
To Remove a Single character from The Given String please find my method hope it will be usefull. i have used str.replaceAll to remove the string but their are many ways to remove a character from a given string but i prefer replaceall method.
Code For Remove Char:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class Removecharacter
{
public static void main(String[] args)
{
String result = removeChar("Java", 'a');
String result1 = removeChar("Edition", 'i');
System.out.println(result + " " + result1);
}
public static String removeChar(String str, char c) {
if (str == null)
{
return null;
}
else
{
return str.replaceAll(Character.toString(c), "");
}
}
}
Console image :
please find The Attached image of console,
Thanks For Asking. :)
public static String removechar(String fromString, Character character) {
int indexOf = fromString.indexOf(character);
if(indexOf==-1)
return fromString;
String front = fromString.substring(0, indexOf);
String back = fromString.substring(indexOf+1, fromString.length());
return front+back;
}
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
String line1=input.readLine();
String line2=input.readLine();
char[] a=line2.toCharArray();
char[] b=line1.toCharArray();
loop: for(int t=0;t<a.length;t++) {
char a1=a[t];
for(int t1=0;t1<b.length;t1++) {
char b1=b[t1];
if(a1==b1) {
StringBuilder sb = new StringBuilder(line1);
sb.deleteCharAt(t1);
line1=sb.toString();
b=line1.toCharArray();
list.add(a1);
continue loop;
}
}
When I have these kinds of questions I always ask: "what would the Java Gurus do?" :)
And I'd answer that, in this case, by looking at the implementation of String.trim().
Here's an extrapolation of that implementation that allows for more trim characters to be used.
However, note that original trim actually removes all chars that are <= ' ', so you may have to combine this with the original to get the desired result.
String trim(String string, String toTrim) {
// input checks removed
if (toTrim.length() == 0)
return string;
final char[] trimChars = toTrim.toCharArray();
Arrays.sort(trimChars);
int start = 0;
int end = string.length();
while (start < end &&
Arrays.binarySearch(trimChars, string.charAt(start)) >= 0)
start++;
while (start < end &&
Arrays.binarySearch(trimChars, string.charAt(end - 1)) >= 0)
end--;
return string.substring(start, end);
}
public String missingChar(String str, int n) {
String front = str.substring(0, n);
// Start this substring at n+1 to omit the char.
// Can also be shortened to just str.substring(n+1)
// which goes through the end of the string.
String back = str.substring(n+1, str.length());
return front + back;
}
I just implemented this utility class that removes a char or a group of chars from a String. I think it's fast because doesn't use Regexp. I hope that it helps someone!
package your.package.name;
/**
* Utility class that removes chars from a String.
*
*/
public class RemoveChars {
public static String remove(String string, String remove) {
return new String(remove(string.toCharArray(), remove.toCharArray()));
}
public static char[] remove(final char[] chars, char[] remove) {
int count = 0;
char[] buffer = new char[chars.length];
for (int i = 0; i < chars.length; i++) {
boolean include = true;
for (int j = 0; j < remove.length; j++) {
if ((chars[i] == remove[j])) {
include = false;
break;
}
}
if (include) {
buffer[count++] = chars[i];
}
}
char[] output = new char[count];
System.arraycopy(buffer, 0, output, 0, count);
return output;
}
/**
* For tests!
*/
public static void main(String[] args) {
String string = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
String remove = "AEIOU";
System.out.println();
System.out.println("Remove AEIOU: " + string);
System.out.println("Result: " + RemoveChars.remove(string, remove));
}
}
This is the output:
Remove AEIOU: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Result: TH QCK BRWN FX JMPS VR TH LZY DG
For example if you want to calculate how many a's are there in the String, you can do it like this:
if (string.contains("a"))
{
numberOf_a++;
string = string.replaceFirst("a", "");
}
I need to delete the set substring from string in Java. How I can to do it?
example:
string st1="The end of the text";
string st2="end of the ";
result:
st1="The text".
You can do this:
String newString = st1.replace(st2, "");
// String newString2 = st1.replaceAll(st2, ""); Alternative
// String newString3 = st1.replaceFirst(st2, ""); Alternative 2
However, your question smell homework so you should add that tag on future questions if this is true.
Java String documentation
Does the following do what you are looking for?
str1 = st1.replace(st2,"");
If you want to use substring(), you can do it like this:
public static String getCustomString(String s1, String s2)
{
if(s1.length() >= s2.length())
{
if(s1.contains(s2))
return s1.substring(0, s1.indexOf(s2)) + s1.substring(s1.indexOf(s2) + s2.length());
}
else
{
if(s2.contains(s1))
return s2.substring(0, s2.indexOf(s1)) + s2.substring(s2.indexOf(s1) + s1.length());
}
return "";
}
If homework (with minimal usage of Java API calls:
public void subString(String st1, String st2) {
int s2len = st2.length();
int s1len = st1.length();
int i = 0;
int count = 0;
while(i <= st1.length() && i+st2.length() <= st1.length()) {
if (st1.substring(i, i+st2.length()).equalsIgnoreCase(st2)) {
st1 = (i > 0? st1.substring(0, i) : "") + st1.substring(i+st2.length());
i=0;
}
else {
i++;
}
}
System.out.println(st1);
}
Otherwise:
st1.replace(st2, "");
Is it possible to reverse String in Java without using any of the temporary variables like String, Char[] or StringBuilder?
Only can use int, or int[].
String reverseMe = "reverse me!";
for (int i = 0; i < reverseMe.length(); i++) {
reverseMe = reverseMe.substring(1, reverseMe.length() - i)
+ reverseMe.substring(0, 1)
+ reverseMe.substring(reverseMe.length() - i, reverseMe.length());
}
System.out.println(reverseMe);
Output:
!em esrever
Just for the fun of it, of course using StringBuffer would be better, here I'm creating new Strings for each Iteration, the only difference is that I'm not introducing a new reference, and I've only an int counter.
The objects of the Java String class are immutable - their contents cannot be altered after being created.
You will need at least two temporary objects - one for the final result and one for the intermediate values - even if you do find a way to avoid using a local variable.
EDIT:
That said, since you can use int[] you may be able to cheat.
Since char can be assigned to int, you can use String.charAt() to create an int array with the character values in reverse order. Or you may be allowed to use String.toCharArray() to get a char array that will be copied over to your int[] temporary.
Then you use the variable that holds the reference to your original string (or the result variable, if you are allowed one) to start from an empty string (easily obtainable with a direct assignment or String.substring()) and use String.concat() to create the final result.
In no case, however, will you be able to swap the characters in-place as you would do in C/C++.
EDIT 2:
Here's my version which does not use StringBuffer/Builders internally:
int r[] = new int[s.length()];
int idx = r.length - 1;
for (int i : s.toCharArray()) {
r[idx--] = i;
}
s = s.substring(0, 0);
for (int i : r) {
s = s.concat(String.valueOf((char)i));
}
String s = "Hello World!";
for(int i = 0; i < s.length(); i++)
{
s = s.substring(1, s.length() - i) + s.charAt(0) + s.substring(s.length() - i);
}
System.out.println(s); // !dlroW olleH
No temporary variables! :)
One of many ways:
String str = "The quick brown fox jumps over the lazy dog";
int len = str.length();
for (int i = (len-1); i >= 0; --i)
str += str.charAt(i);
str = str.substring(len);
System.out.println(str);
public String reverseStr(String str) {
if (str.length() <= 1) {
return str;
}
return reverseStr(str.substring(1)) + str.charAt(0);
}
Because you can use an int, you can assign an int a char value:
String aString = "abc";
int intChar = aString.charAt(0);
You will have to convert from the int back to the char to assign it to aString.charAt(2).
I'm sure you can figure it out from there.
First append the string to itself in reverse manner. Then take the second half out of it.
public class RevString {
public static void main(String[] args) {
String s="string";
for(int i=s.length()-1;i>=0;i--){
s+=s.charAt(i);
}
s=s.substring(s.length()/2, s.length());
System.out.println(s);
}
}
Without using any collection,StringBulider, StringBuffer or temp array reverse the string. Simple and crisp:
public static void main(String[] args) {
String test = "Hello World";
String rev = "";
Pattern p = Pattern.compile("[\\w|\\W]");
Matcher m = p.matcher(test);
while (m.find()) {
rev = m.group()+rev;
}
System.out.println("Reverse==" + rev);
}
Output
Reverse==dlroW olleH
Hope it helps :)
public class Test {
static St`enter code here`ring reverseString(String str) {
for (int i = 0; i < str.length() / 2; i++) {
if (i == 0) {
str = str.charAt(str.length() - 1 - i) + str.substring(i + 1, str.length() - 1 - i) + str.charAt(i);
} else {
str = str.substring(0, i) + str.charAt(str.length() - 1 - i)
+ str.substring(i + 1, str.length() - 1 - i) + str.charAt(i)
+ str.substring(str.length() - i, str.length());
}
}
return str;
}
public static void main(String args[]) {
String s = "ABCDE";
System.out.println(Test.reverseString(s));
}
}
String str = "Welcome";
for(int i=0;i<str.length();){
System.out.print(str.charAt(str.length()-1));
str = str.substring(0,str.length()-1);
}
Except for loop variables.
You can use class java.lang.StringBuilder:
String reservedString = new StringBuilder(str).reserve().toString();