I have a method that supposed to delete all the dups from string passed inside it. I can print the dups, how can I delete them in the original string ? Say, 'miami' will need to be 'mia' when it will return. Thanks.
public static String removeDups( String str1){
char[] str = str1.toCharArray();
if (str == null) return null;
int len = str.length;
if (len < 2) return new String(str);
char[] newStr = new char[len+1];
int copyLength = 0;
for ( int i = 1 ; i < len; i++){
for( int j=0; j< i; j++){
if ( str[i] == str[j]){
System.out.println(" str[i] == str[j] = "+ str[i] + " , "+str[j]);
break;
}
}
}
return new String(str);
}
I found this to be easier using a StringBuilder rather than a String
EDIT
This can also be done with a combination of StringBuilder and regex
Regex Pattern breakdown:
(.) --> matches any character and puts in group 1.
?= --> this is called a positive lookahead.
?=.*\\1 --> positive lookahead of zero or more characters for the first group
Code Sample:
public static void main(String[] args) throws Exception {
System.out.println(removeDuplicates("miamimiamimiami"));
System.out.println(removeDuplicatesRegex("miamimiamimiami"));
}
public static String removeDuplicates(String input){
StringBuilder data = new StringBuilder(input);
for (int i = 0; i < data.length(); i++) {
String character = String.valueOf(data.charAt(i));
int dupIndex = data.indexOf(character, i + 1);
while (dupIndex != -1) {
data.deleteCharAt(dupIndex);
dupIndex = data.indexOf(character, i + 1);
}
}
return data.toString();
}
public static String removeDuplicatesRegex(String input) {
return new StringBuilder(
new StringBuilder(input)
.reverse()
.toString()
.replaceAll("(.)(?=.*\\1)", ""))
.reverse().toString();
}
Results:
mia
mia
Here's another option:
StringBuffer buf = new StringBuffer( originalString);
int len = str.length();
for (int i = 0; i < len; i++) {
char c = buf.charAt( i );
for (int j = len - 1; j > i; j--) {
if ( buf.charAt( j ) == c ) {
buf.deleteCharAt( j );
len--;
}
}
}
Remove all duplicate chars in a String:
public static String removeDuplicates(String str1) {
if (str1 == null)
return null;
char[] str = str1.toCharArray();
int len = str.length;
if (len < 2)
return str1;
char temp = str[0];
for (int i = 1; i < len; i++) {
if (temp != 0)
for (int j = i; j < len; j++)
if (temp == str[j])
str[j] = 0;
temp = str[i];
}
int i = 0;
char[] str2 = new char[len];
for (char c : str)
if (c != 0)
str2[i++] = c;
return (new String(str2)).trim();
}
You can also use Arraylist to store the unique characters:
public static String removeDups( String str1){
ArrayList<Character> set=new ArrayList<Character>();
char[] str=str1.toCharArray();
for(int i=0;i<str.length;i++)
{
if(!set.contains(str[i])){
set.add(str[i]);
}
}
for(char e:set)
{
System.out.print(e);
}
}
Your loop seems to be a bit strange.
char[] str = str1.toCharArray();
int len = str.length;
if (str == null || len < 2) return null;
char[] newStr = new char[len+1];
int newStrLength = 0;
for( int i = 1; i < len; i++ ){ //Iterate complete string
for( int j=0; j < i; j++ ){ //Iterate the already-finished part
if( str[i] == str[j] )
break;
}
newStr[newStrLength++] = str[i];
}
}
newStr[newStrLength] = 0;
In this example I make a completly new string and don't alter the original one. It makes the code clearer to read.
Alternatively you could take a look at this question which has some more efficient answers.
Related
package adc;
import java.util.*;
public class bca {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the sentence to decrypt");
String s=sc.nextLine();
char[] ans = s.toCharArray();
int len=s.length();
char[] sol= new char[len];
System.out.println("len="+s.length());
for(int i=0;i<len;i++) {
int j=i;
if(ans[i]=='1') {
sol[i]=ans[i-1];
}
else if(ans[i]=='2') {
sol[i]=ans[i-1];
sol[i+1]=ans[i-1];
}
else {
sol[i]=ans[i];
}
System.out.print(sol[i]);
}
sc.close();
}
}
new here learning java tring to get some help here thank you.
Enter the sentence to decrypt
Input:o1ps o2ps
output:len=9
oops oopsis it possible to make o2ps has ooops
You need different counters for the input string and the output string, however, as you don't know in advance the length of the output string, you can use a StringBuilder:
char[] ans = s.toCharArray();
StringBuilder out = new StringBuilder();
System.out.println("len=" + s.length());
for (int i = 0; i < ans.length; i++) {
if (i > 0 && ans[i] >= '0' && ans[i] <= '9') {
char prev = ans[i-1];
int count = ans[i] - '0';
for (int j = 0; j < count; ++j) {
out.append(prev);
}
} else {
out.append(ans[i]);
}
}
System.out.println("output=" + out);
UPDATE:
To also reverse words:
char[] ans = s.toCharArray();
List<String> words = new ArrayList<>();
StringBuilder out = new StringBuilder();
System.out.println("len=" + s.length());
for (int i = 0; i < ans.length; i++) {
if (ans[i] == ' ') {
if (out.length() > 0) {
words.add(out.toString());
out.setLength(0);
}
} else if (i > 0 && ans[i] >= '0' && ans[i] <= '9') {
char prev = ans[i-1];
int count = ans[i] - '0';
for (int j = 0; j < count; ++j) {
out.append(prev);
}
} else {
out.append(ans[i]);
}
}
if (out.length() > 0) {
words.add(out.toString());
}
Collections.reverse(words);
String output = words.stream().collect(Collectors.joining(" "));
System.out.println("output=" + output);
public class test
{
static Scanner store = new Scanner(System.in);
public static void main(String[] args)
{
String str1 = args[0];
String str2 = args[1];
System.out.printf("%nThere are %d dissimilar characters in the two strings.%n", CountNotSim(str1, str2));
}
public static int CountNotSim(String str1, String str2)
{
String s1 = str1.toLowerCase();
String s2 = str2.toLowerCase();
char[] a1 = new char[s1.length()];
char[] a2 = new char[s2.length()];
for (int g = 0; g < s1.length(); g++)
a1[g] = s1.charAt(g);
for (int h = 0; h < s2.length(); h++)
a2[h] = s2.charAt(h);
int check = 0, stored;
char[] array = new char[26];
int ctr = s1.length() + s2.length();
for (int i = 0; i < a1.length; i++)
{
check = 0;
stored = 0;
for (int j = 0; j < a2.length; j++)
{
if (a1[i] == a2[j])
{
check++;
for (int k = 0; k < 26; k++)
{
if (array[k] == ' ')
if (stored == 0)
array[k] = a1[i];
if (a1[i] == array[k])
{
stored = 1;
break;
}
}
System.out.print(stored + "/ ");
}
}
if (check > 0)
{
if (stored == 0)
ctr -= (check + 1);
else if (stored == 1)
ctr--;
}
System.out.print(ctr + " "); //checker
}
System.out.println();
return ctr;
}
}
The program checks for dissimilar letters in two strings inputted from the command line. Variable "stored" is supposed to change to 1 whenever there's a match to avoid extra deductions to variable "ctr". However, for some reason, not only does "stored's" value not change, the array "array" also doesn't update its elements whenever there's a match. I'm at a loss on how to fix it--nothing looks incorrect.
You wrote this:
char[] array = new char[26];
...
for (int k = 0; k < 26; k++)
{
if (array[k] == ' ') {
...
But you simply set the length of array not its content.
As a char array, it's filled with the default char value, which is not the character space but the value 0 (not the character 0, but the numeric value 0)
So array[k] == ' ' will never be true.
Try with that:
for (int k = 0; k < 26; k++)
{
if (array[k] == 0) {
...
I'm trying to combine two sentences word by word in java without using any special string methods except charAt and length.
It's like
String s1="hello world";
String s2="programmers are greeting"
I want to combine that two string get one word from s1 then get one word from s2 and keep until there is no word left in s1 and s2 in s3.
String s3="hello programmers world are greeting"
Here's my method but when I run it doesn't return anything. I couldn't find the problem:
void combine(String str1, String str2) {
int i,
j,
sl1,
sl2,
s,
test;
sl1 = str1.length();
sl2 = str2.length();
test = sl1 + sl2;
char[] ar1 = new char[sl1];
char[] ar2 = new char[sl2];
for (i = 0; i < ar1.length; i++)
{
ar1[i] = str1.charAt(i);
}
for (j = 0; j < ar2.length; j++)
{
ar2[j] = str2.charAt(j);
}
char[] array = new char[test];
s = array.length;
i = 0;
j = 0;
while (s <= i + j) {
while (ar1[i] != ' ')
{
if (i == sl1) break;
array[i + j] = ar1[i];
i = i + 1;
}
while (ar2[j] != ' ')
{
if (j == sl2) break;
array[j + i] = ar2[j];
j = j + 1;
}
}
for (i = 0; i < s; i++)
{
System.out.print(array[i]);
}
}
The method combine is void which should become int otherwise you should output the answer using a System.out.println();
I want to print the statement System.out.println(sb.append(ss));
Only the last time I tried to take it out of the for loop but the result is wrong.
public static String constatmentvertBinaryStringToString(String string) {
StringBuilder sb = new StringBuilder();
char[] chars = string.toCharArray();
String ss = null;
//for each character
for (int j = 0; j < chars.length; j += 8) {
int idx = 0;
int sum = 0;
//for each bit in reverse
for (int i = 7; i >= 0; i--) {
if (chars[i + j] == '1') {
sum += 1 << idx;
}
idx++;
}
System.out.println(sum); //debug
int div = sum / 4;
System.out.println(div);
System.out.println((char) div);
int rem = sum % 4;
System.out.println(rem);
ss = (char) div + "" + rem;
System.out.println(sb.append(ss));
}
return sb.toString();
}
Put System.out.println(sb.append(ss)); out of the loop:
public static String constatment vertBinaryStringToString(String string){
StringBuilder sb = new StringBuilder();
char[] chars = string.toCharArray();
String ss=null;
//for each character
for (int j = 0; j < chars.length; j+=8) {
int idx = 0;
int sum =0;
//for each bit in reverse
for (int i = 7; i>= 0; i--) {
if (chars[i+j] == '1') {
sum += 1 << idx;
}
idx++;
}
System.out.println(sum); //debug
int div=sum/4;
System.out.println(div);
System.out.println((char)div);
int rem=sum%4;
System.out.println(rem);
ss=(char)div+""+rem;
}
System.out.println(sb.append(ss));
return sb.toString();
}
Because System.out.println(sb.append(ss)); contains a call to sb.append(ss)); taking the statement out of the for loop will have a different result than the one expected.
You should keep sb.append(ss); inside the loop and add System.out.println(sb) outside the loop.
public static String constatmentvertBinaryStringToString(String string) {
StringBuilder sb = new StringBuilder();
char[] chars = string.toCharArray();
String ss = null;
//for each character
for (int j = 0; j < chars.length; j += 8) {
int idx = 0;
int sum = 0;
//for each bit in reverse
for (int i = 7; i >= 0; i--) {
if (chars[i + j] == '1') {
sum += 1 << idx;
}
idx++;
}
System.out.println(sum); //debug
int div = sum / 4;
System.out.println(div);
System.out.println((char) div);
int rem = sum % 4;
System.out.println(rem);
ss = (char) div + "" + rem;
sb.append(ss);
}
System.out.println(sb);
return sb.toString();
}
The program I am writing is to generate every possible sub-string from a given string (including the word itself) and store these into a String array
This is my code:
String word = "WOMAN";
String[] res = new String[20];
String sub;
int i, j, k;
int len = word.length();
for(i = 0; i < len; i++)
{
for(j = 0; j <= len-i; j++)
{
sub = word.substring(i, i+j);
for(k = 0; k < res.length; k++)
res[k] = sub;
}
}
I get an error that says - error: incompatible types: String[] cannot be converted to String. What am I doing wrong?! I want to store each sub-string as an element in the res array.
public static String[] getSubStrings(String string){
List<String> result = new ArrayList<String>();
int i, c, length;
length = string.length();
for( c = 0 ; c < length ; c++ )
{
for( i = 1 ; i <= length - c ; i++ )
{
result.add(string.substring(c, c+i));
}
}
return result.toArray(new String[result.size()]);
}
i change little maybe for some help
String word = "WOMAN";
String[] res = new String[20];
String sub;
int i, j, k=0;
int len = word.length();
for(i = 0;i < len;i++)
{
for(j = 0;j <= len-i;j++,k++)
{
sub = word.substring(i, i+j);
//for(k = 0;k < res.length;k++)
res[k] = sub;
}
}
Try it this way
String word = "WOMAN";
String sub = "";
int len = word.length();
List list = new ArrayList();
for(int i = 0; i < len; i++)
{
for(int j = 1; j <=len-i; j++)
{
sub = word.substring(i, i+j);
list.add(sub);
}
}
System.out.println(list);
Try Using ArrayList in place of array . Array Size is fixed . So generated sub strings can sometimes over flow or some spaces remain empty if sub string size will be less than the array. Array list grows dynamically with the increasing size .
with Array list one simple solution would be :
public class GenerateStrings {
/**
* Generate substrings of a given string and add them in an arraylist.
*/
public static void main(String[] args) {
ArrayList<String> aList=new ArrayList<String>();
Scanner sc = new Scanner(System.in);
System.out.println("enter the string to split");
String string=sc.nextLine();
for(int i=0;i<string.length();i++){
for(int j=1;j<=string.length()-i;j++){
String subString=string.substring(i, i+j);
aList.add(subString);
}
}
System.out.println(aList);
}
}
I Hope it helps .
I simplified your code to this one. This might help.
String str = "WOMAN";
List<String> tempArr = new ArrayList<String>();
for (int i = 1; i < str.length(); i++) {
for (int j = i; j <= str.length(); j++) {
tempArr.add(str.substring(i - 1, j));
}
}
String[] res = tempArr.toArray(new String[tempArr.size()]);