Printing last index of string in a string without using lastIndexOf method - java

Note: This question is asked for a school assignment. I fell I'm getting close to the true code, there are only a few points left to be taken care of.
I am asked to write a method that receives two strings(s1 and s2) and
checks whether s2 is in s1 case sensitively. If s2 is in s1 it returns the index of the last occurrence of s2, otherwise it returns -1.
So, here is my code:
import java.util.*;
public class homework4 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("\nEnter a choice: ");
int choice = input.nextInt();
if(choice == 1) {
System.out.println("Enter firts string: ");
String s1 = input.next();
System.out.println("Enter second string: ");
String s2 = input.next();
System.out.print(contains(s1,s2));
}
else {
//Call other methods...
}
public static int contains (String s1, String s2) {
for(int i = 0; i<s1.length(); i++) {
for(int j = 0; j<s2.length(); j++) {
char ch = s2.charAt(j);
if(s1.charAt(i) == ch) {
return i;
}
}
}
return -1;
}
But this method returns first index of s2 or it is just a copy of IndexOf method.
Output for s1 = aabbccbbe and s2 = bb is 2.
EDIT : #eli's code
import java.util.*;
public class homework4 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("\nEnter a choice: ");
int choice = input.nextInt();
if(choice == 1) {
System.out.println("Enter firts string: ");
String s1 = input.next();
System.out.println("Enter second string: ");
String s2 = input.next();
System.out.print(contains(s1,s2));
}
else {
//Call other methods...
}
public static int contains(String s1, String s2) {
int i = s2.length()-1, j = s1.length()-1;
if(i > j)
return -1;
for(; i > -1; i--) {
for(; j >= 0; j--) {
if(s1.charAt(j) == s2.charAt(i)) {
if(i == 0)
return j;
if(j != 0)
j--;
break;
} else if(i != s2.length()) {
i = s2.length()-1;
}
}
}
return -1;
}

First of all, close any resource you open when you're done with it.
input.close();
If it is allowed you can just use regex:
public static int contains (String s1, String s2) {
Pattern p = Pattern.compile(s2+"(?!.*"+s2+")");
Matcher m = p.matcher(s1);
if(m.find())
return m.start();
return -1;
}
The regex pattern is explained here.
With find() you make sure that at least one occurrence is present.
As the pattern can result in 1 and only 1 result, you can just ask for the "first index of first occurrence" in the matcher, achieved with start().
EDIT
Okay, I can see you can't use anything but charAt and length.
Here's a different solution without regex, substring, indexOf or what-so-ever:
public static int contains(String s1, String s2) {
int i = s2.length()-1, j = s1.length()-1;
if(i > j)
return -1;
for(; i > -1; i--) {
for(; j >= 0; j--) {
if(s1.charAt(j) == s2.charAt(i)) {
if(i == 0)
return j;
if(j != 0)
j--;
break;
} else if(i != s2.length()) {
i = s2.length()-1;
}
}
}
return -1;
}
I must admit I didn't thoroughly test this.
FINAL
I've done some minor fixes for you. I don't know how you were capable of compiling what you edited in your post. Here's a working sample:
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class homework4 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter choice: ");
switch (input.nextInt()) {
// If 1 is given as input...
case 1:
// As we press "enter" after inputting 1, the newline is read by the
// scanner. We skip this newline by doing this.
input.nextLine();
System.out.println("Enter first string: ");
String s1 = input.nextLine();
System.out.println("Enter second string: ");
String s2 = input.nextLine();
System.out.println("Result: " + contains(s1, s2));
break;
// If 2 is given as input (just for the sake of the example)
case 2:
System.out.println("You chose an unimplemented choice.");
break;
// If something else is given as input...
default:
System.out.println("Nothing to do...");
break;
}
// As Scanner is considered a resource, we have to close it, now that
// we're done using it.
input.close();
}
// This is the RegEx implementation
public static int containsRegx(String s1, String s2) {
Pattern p = Pattern.compile(s2 + "(?!.*" + s2 + ")");
Matcher m = p.matcher(s1);
if (m.find())
return m.start();
return -1;
}
// This is the charAt and length only
public static int contains(String s1, String s2) {
int i = s2.length() - 1, j = s1.length() - 1;
if(i > j || i * j == 0)
return -1;
for (; i > -1; i--) {
for (; j >= 0; j--) {
if (s1.charAt(j) == s2.charAt(i)) {
if (i == 0)
return j;
if (j != 0)
j--;
break;
} else if (i != s2.length()) {
i = s2.length() - 1;
}
}
}
return -1;
}
}

I think it will boil down to looping through string characters and storing the last index of occurred match.
Here is not perfect, but simple example without use of indexOf:
public static int contains(String s1, String s2) {
if(s1.length() < s2.length())
return -1;
int lastOccurrence = -1;
for (int i = 0; i < s1.length(); ) {
if (s1.startsWith(s2, i)) {
lastOccurrence = i + s2.length() - 1;
i = lastOccurrence + 1;
}
else {
++i;
}
}
return lastOccurrence;
}

Say you have the string called sentence: The quick brown fox jumps over the lazy dog. and you want to find the last occurrence of "the", called token.
sentence.length = 44 and token.length = 3
Consider this somewhat java pseudo code:
public static int lastIndexOf(String sentence, String token) {
//The starting index is the first possible location your token could fit
int startingIndex = sentence.length() - token.length();
//move backwards one character at a time until you reach 0
//checking for string fragment that equals your token at each iteration
for (int i = startingIndex; i >= 0; i--) {
String fragment = sentence.substring(i, i + token.length());
if (fragment.equals(token)) return i;
}
return -1;
}
EDIT
Here is the full application using only length and charAt():
public class HelloWorld
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
int indexOf = lastIndexOf("The quick brown fox jumps over the lazy dog.", "the");
System.out.print(indexOf);
}
public static int lastIndexOf(String sentence, String token) {
int startingIndex = sentence.length() - token.length();
for (int i = startingIndex; i >= 0; i--) {
String fragment = substring(sentence, i, i + token.length());
if (strEquals(token, fragment)) return i;
}
return -1;
}
public static String substring(String str, int startingIndex, int endingIndex) {
int size = endingIndex - startingIndex;
char[] arr = new char[size];
for (int i = 0; i < size; i++) {
arr[i] = str.charAt(startingIndex+i);
}
return new String(arr);
}
public static boolean strEquals(String s1, String s2) {
if (s1.length() != s2.length()) return false;
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) == s2.charAt(i)) continue;
return false;
}
return true;
}
}
EDIT 2
You also have a bug in the way you are reading your input. You need to use input.readLine() to get the full line. input.read breaks on spaces. Along those lines, you also need a new scanner for each line you want to read.
EDIT 3
Here is the whole source:
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args)
{
Scanner input1 = new Scanner(System.in);
System.out.println("\nEnter a choice: ");
String s1="";
String s2="";
int choice = input1.nextInt();
if(choice == 1) {
Scanner input2 = new Scanner(System.in);
System.out.println("Enter first string: ");
s1 = input2.nextLine();
Scanner input3 = new Scanner(System.in);
System.out.println("Enter second string: ");
s2 = input3.nextLine();
}
int indexOf = lastIndexOf(s1, s2);
System.out.println(indexOf);
}
public static int lastIndexOf(String sentence, String token) {
int startingIndex = sentence.length() - token.length();
for (int i = startingIndex; i >= 0; i--) {
String fragment = substring(sentence, i, i + token.length());
if (strEquals(token, fragment)) return i;
}
return -1;
}
public static String substring(String str, int startingIndex, int endingIndex) {
int size = endingIndex - startingIndex;
char[] arr = new char[size];
for (int i = 0; i < size; i++) {
arr[i] = str.charAt(startingIndex+i);
}
return new String(arr);
}
public static boolean strEquals(String s1, String s2) {
if (s1.length() != s2.length()) return false;
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) == s2.charAt(i)) continue;
return false;
}
return true;
}
}

Related

I want to check substring from last to first. How can I fix my code?

I want to check if pattern is substring of s, But I want to check it from last to first index.
For Example
s="Hello How Are you";
pattern="Are"
and it returns the index of e->12. because from last to first in pattern string we first see letter e.
in the below, I take my code.
How can I fix it?
class Main {
static int find(String s1, String s2) {
int M = s1.length();
int N = s2.length();
for (int i = N - 1; i >= 0; i--) {
int j;
for (j = M - 1; j >= 0; j--)
if (s2.charAt(i) != s1.charAt(j))
break;
if (j == 0)
return i;
}
return -1;
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter first String: ");
String s = scanner.nextLine();
System.out.println("Please Enter Pattern String: ");
String pat = scanner.nextLine();
int res = find(pat, s);
if (res == -1)
System.out.println(res);
else
System.out.println("Present at index " + res);
}
}
Note that when you iterate over the pattern, you should also maintain some iteration on the substring of the "first string", such that you compare each letter in the pattern to the relevant letter in the substring. Something like that:
static int find(String s1, String s2) {
int M = s1.length();
int N = s2.length();
for (int i = N-1; i >=0; i--) {
int j;
int k = i;
for (j = M-1; j >0; j--)
if (s2.charAt(k) != s1.charAt(j))
break;
else
k--;
if(j==0)
return k + (M-1);
}
return -1;
}
Since you are using java, there is a simpler way.
public class Main {
static int find(String s1, String s2) {
return s1.lastIndexOf(s2)+s2.length()-1;
}
public static void main(String[] args) {
String str = "Hello How Are you";
String pattern = "Are";
System.out.println(find(str,pattern));
}
}

How do I code a recursive a recursive method that forms the integer sum of all valid numerics substrings in a string?

For example, the result of toNumber("3.2ac4.8rw2") would be 10 (=3.2+4.8+2).
My Code that I created is below. However it is failing at what I tend to do and I cannot come up with a solution.
public class toNumber {
public static int toNumber(String s) {
if (s == null || s.length() == 0) {
return 0;
}
char next = s.charAt(0);
if (Character.isDigit(next)) {
return Character.digit(next, 10) + toNumber(s.substring(1));
}
else
{
return toNumber(s.substring(1));
}
}
public static int to1Number(String input)
{
if(input ==null || input.length()==0)
return 0;
if(Character.isDigit(input.charAt(input.length()-1)))
return input.charAt(input.length()-1) +
toNumber(input.substring(0, input.length()-1));
else
return toNumber(input.substring(0, input.length()-1));
}
public static void main(String []args)
{
String input;
Scanner kb = new Scanner(System.in);
System.out.println("please enter some input");
input = kb.nextLine();
System.out.println(to1Number(input));
}
}
**I Tested it like this **
please enter some input
my input: t4343
result returned: 62
If you need it recursive:
public int toNumber(String str) {
char ch = str.charAt(0);
int count = Character.isDigit(ch) ? Character.getNumericValue(ch) : 0;
return str.length() > 1 ? count + toNumber(str.substring(1)) : count;
}
Or java 8 using streams without recursion:
public int toNumber(String str) {
return str.chars()
.mapToObj(i->(char)i)
.filter(Character::isDigit)
.mapToInt(Character::getNumericValue)
.sum();
}
Or with a standard loop without recursion:
public int toNumber(String str) {
int count = 0;
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(Character.isDigit(ch)) {
count += Character.getNumericValue(ch);
}
}
return count;
}
If you also want to count floating numbers, a solution using regular expressions would be the simpler one:
private double toNumber(String str) {
ArrayList<String> nums = new ArrayList<>();
Pattern pattern = Pattern.compile("\\d+(\\.\\d*)?"); // If you want to limit the decimal count to 1: "\\d{1}(\\.\\d{1})?"
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
nums.add(matcher.group());
}
return nums.stream().mapToDouble(Double::valueOf).sum();
}

How to count substring of a string has appeared in another large string?

I have a large string like " ali li vali bali", and I want to know that how many times all words(I mean individual words like li) are repeated (ali, li, vali and bali are only considered as substrings) apart from its own existence.
For example: li is substring in a large string and it is repeating thrice other than its own existence.
li in ali, li in vali and li in bali. count is: 3.
This is my code and the error I got:
import java.util.*;
public class main{
public static void main(String args[]){
String str="";
Scanner scan= new Scanner(System.in);
while(scan.hasNext())
{
str+= scan.nextLine();
}
int n= str.trim().split("\\s+").length;
String[] wordsArray=str.split(" ");
substring sub=new substring();
for(int i=0;i<wordsArray.length;i++){
int count=sub.sub(wordsArray[i],str);
csub+=count;
}
System.out.println("number of substring: "+csub);
and substring do:
public class substring{
public int sub(String str,String str2){
String[] wordsArray=str2.split(" ");
int len=str.length();
int b=0;
String[] str1=new String[len*2+2];
int k=0;
for (int from = 0; from < str.length(); from++) {
for (int to = from + 1; to <= str.length(); to++) {
str1[k]=str.substring(from, to);
k++;
}
}
int index = 0;
int count = 0;
for(int i=0;i<str1.length;i++){
if(str1[i].length()>2){
while ((index = str2.indexOf(str1[i], index)) != -1) {
index += str1[i].length();
count++;
b++;
}
}
}
return b;
}
}
What is wrong?
**I got this error:**
Expection in thread "main" java lang.NullPointerExpection
at substring.sub<substring.java:20>
at main.main<main.java:52>
You can just scan the string without splitting it.
Example:
public static int countSubstring(String str, String substring) {
// start at the beggining of the string
int pos = 0;
int count = 0;
// search starting at pos and store the index (if found) on pos
while ((pos = str.indexOf(substring, pos)) != -1) {
count++;
// pos is at the index of last found substring
// advance it by the length of the substring
pos = pos + substring.length();
}
return count;
}
public static void main(String[] args) {
System.out.println(countSubstring("li, vali and bali", "li"));
}
Output
3
You could do it like this,
public static int sub(String str, String str2) {
if (str == null || str2 == null) {
return 0;
}
int count = 0;
int p = str2.indexOf(str);
while (p >= 0) {
count++;
p = str2.indexOf(str, p + str.length());
}
return count;
}
public static void main(String[] args) throws Exception {
String toSearch = "Hi Dee Hi";
System.out.println(sub("Hi", toSearch));
System.out.println(sub("Dee", toSearch));
System.out.println(sub("Ho", toSearch));
}
Outputs
2
1
0

How to remove duplicate character from a string in java?

In my program, the user enters a string, and it first finds the largest mode of characters in the string. Next, my program is supposed to remove all duplicates of a character in a string, (user input: aabc, program prints: abc) which I'm not entirely certain on how to do. I can get it to remove duplicates from some strings, but not all. For example, when the user puts "aabc" it will print "abc", but if the user puts "aabbhh", it will print "abbhh." Also, before I added the removeDup method to my program, it would only print the maxMode once, but after I added the removeDup method, it began to print the maxMode twice. How do I keep it from printing it twice?
Note: I cannot convert the strings to an array.
import java.util.Scanner;
public class JavaApplication3 {
static class MyStrings {
String s;
void setMyStrings(String str) {
s = str;
}
int getMode() {
int i;
int j;
int count = 0;
int maxMode = 0, maxCount = 1;
for (i = 0; i< s.length(); i++) {
maxCount = count;
count = 0;
for (j = s.length()-1; j >= 0; j--) {
if (s.charAt(j) == s.charAt(i))
count++;
if (count > maxCount){
maxCount = count;
maxMode = i;
}
}
}
System.out.println(s.charAt(maxMode)+" = largest mode");
return maxMode;
}
String removeDup() {
getMode();
int i;
int j;
String rdup = "";
for (i = 0; i< s.length(); i++) {
int count = 1;
for (j = 0; j < rdup.length(); j++) {
if (s.charAt(i) == s.charAt(j)){
count++;
}
}
if (count == 1){
rdup += s.charAt(i);
}
}
System.out.print(rdup);
System.out.println();
return rdup;
}
}
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
MyStrings setS = new MyStrings();
String s;
System.out.print("Enter string:");
s = in.nextLine();
setS.setMyStrings(s);
setS.getMode();
setS.removeDup();
}
}
Try this method...should work fine!
String removeDup()
{
getMode();
int i;
int j;
String rdup = "";
for (i = 0; i< s.length(); i++) {
int count = 1;
for (j = i+1; j < s.length(); j++) {
if (s.charAt(i) == s.charAt(j)) {
count++;
}
}
if (count == 1){
rdup += s.charAt(i);
}
}
// System.out.print(rdup);
System.out.println();
return rdup;
}
Welcome to StackOverflow!
You're calling getMode() both outside and inside of removeDup(), which is why it's printing it twice.
In order to remove all duplicates, you'll have to call removeDup() over and over until all the duplicates are gone from your string. Right now you're only calling it once.
How might you do that? Think about how you're detecting duplicates, and use that as the end condition for a while loop or similar.
Happy coding!
Shouldn't this be an easier way? Also, i'm still learning.
import java.util.*;
public class First {
public static void main(String arg[])
{
Scanner sc= new Scanner(System.in);
StringBuilder s=new StringBuilder(sc.nextLine());
//String s=new String();
for(int i=0;i<s.length();i++){
String a=s.substring(i, i+1);
while(s.indexOf(a)!=s.lastIndexOf(a)){s.deleteCharAt(s.lastIndexOf(a));}
}
System.out.println(s.toString());
}
}
You can do this:
public static void main(String[] args) {
String str = new String("PINEAPPLE");
Set <Character> letters = new <Character>HashSet();
for (int i = 0; i < str.length(); i++) {
letters.add(str.charAt(i));
}
System.out.println(letters);
}
I think an optimized version which supports ASCII codes can be like this:
public static void main(String[] args) {
System.out.println(removeDups("*PqQpa abbBBaaAAzzK zUyz112235KKIIppP!!QpP^^*Www5W38".toCharArray()));
}
public static String removeDups(char []input){
long ocr1=0l,ocr2=0l,ocr3=0;
int index=0;
for(int i=0;i<input.length;i++){
int val=input[i]-(char)0;
long ocr=val<126?val<63?ocr1:ocr2:ocr3;
if((ocr& (1l<<val))==0){//not duplicate
input[index]=input[i];
index++;
}
if(val<63)
ocr1|=(1l<<val);
else if(val<126)
ocr2|=(1l<<val);
else
ocr3|=(1l<<val);
}
return new String(input,0,index);
}
please keep in mind that each of orc(s) represent a mapping of a range of ASCII characters and each java long variable can grow as big as (2^63) and since we have 128 characters in ASCII so we need three ocr(s) which basically maps the occurrences of the character to a long number.
ocr1: (char)0 to (char)62
ocr2: (char)63 to (char)125
ocr3: (char)126 to (char)128
Now if a duplicate was found the
(ocr& (1l<<val))
will be greater than zero and we skip that char and finally we can create a new string with the size of index which shows last non duplicate items index.
You can define more orc(s) and support other character-sets if you want.
Can use HashSet as well as normal for loops:
public class RemoveDupliBuffer
{
public static String checkDuplicateNoHash(String myStr)
{
if(myStr == null)
return null;
if(myStr.length() <= 1)
return myStr;
char[] myStrChar = myStr.toCharArray();
HashSet myHash = new HashSet(myStrChar.length);
myStr = "";
for(int i=0; i < myStrChar.length ; i++)
{
if(! myHash.add(myStrChar[i]))
{
}else{
myStr += myStrChar[i];
}
}
return myStr;
}
public static String checkDuplicateNo(String myStr)
{
// null check
if (myStr == null)
return null;
if (myStr.length() <= 1)
return myStr;
char[] myChar = myStr.toCharArray();
myStr = "";
int tail = 0;
int j = 0;
for (int i = 0; i < myChar.length; i++)
{
for (j = 0; j < tail; j++)
{
if (myChar[i] == myChar[j])
{
break;
}
}
if (j == tail)
{
myStr += myChar[i];
tail++;
}
}
return myStr;
}
public static void main(String[] args) {
String myStr = "This is your String";
myStr = checkDuplicateNo(myStr);
System.out.println(myStr);
}
Try this simple answer- works well for simple character string accepted as user input:
import java.util.Scanner;
public class string_duplicate_char {
String final_string = "";
public void inputString() {
//accept string input from user
Scanner user_input = new Scanner(System.in);
System.out.println("Enter a String to remove duplicate Characters : \t");
String input = user_input.next();
user_input.close();
//convert string to char array
char[] StringArray = input.toCharArray();
int StringArray_length = StringArray.length;
if (StringArray_length < 2) {
System.out.println("\nThe string with no duplicates is: "
+ StringArray[1] + "\n");
} else {
//iterate over all elements in the array
for (int i = 0; i < StringArray_length; i++) {
for (int j = i + 1; j < StringArray_length; j++) {
if (StringArray[i] == StringArray[j]) {
int temp = j;//set duplicate element index
//delete the duplicate element by copying the adjacent elements by one place
for (int k = temp; k < StringArray_length - 1; k++) {
StringArray[k] = StringArray[k + 1];
}
j++;
StringArray_length--;//reduce char array length
}
}
}
}
System.out.println("\nThe string with no duplicates is: \t");
//print the resultant string with no duplicates
for (int x = 0; x < StringArray_length; x++) {
String temp= new StringBuilder().append(StringArray[x]).toString();
final_string=final_string+temp;
}
System.out.println(final_string);
}
public static void main(String args[]) {
string_duplicate_char object = new string_duplicate_char();
object.inputString();
}
}
Another easy solution to clip the duplicate elements in a string using HashSet and ArrayList :
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
public class sample_work {
public static void main(String args[]) {
String input = "";
System.out.println("Enter string to remove duplicates: \t");
Scanner in = new Scanner(System.in);
input = in.next();
in.close();
ArrayList<Character> String_array = new ArrayList<Character>();
for (char element : input.toCharArray()) {
String_array.add(element);
}
HashSet<Character> charset = new HashSet<Character>();
int array_len = String_array.size();
System.out.println("\nLength of array = " + array_len);
if (String_array != null && array_len > 0) {
Iterator<Character> itr = String_array.iterator();
while (itr.hasNext()) {
Character c = (Character) itr.next();
if (charset.add(c)) {
} else {
itr.remove();
array_len--;
}
}
}
System.out.println("\nThe new string with no duplicates: \t");
for (int i = 0; i < array_len; i++) {
System.out.println(String_array.get(i).toString());
}
}
}
your can use this simple code and understand how to remove duplicates values from string.I think this is the simplest way to understand this problem.
class RemoveDup
{
static int l;
public String dup(String str)
{
l=str.length();
System.out.println("length"+l);
char[] c=str.toCharArray();
for(int i=0;i<l;i++)
{
for(int j=0;j<l;j++)
{
if(i!=j)
{
if(c[i]==c[j])
{
l--;
for(int k=j;k<l;k++)
{
c[k]=c[k+1];
}
j--;
}
}
}
}
System.out.println("after concatination lenght:"+l);
StringBuilder sd=new StringBuilder();
for(int i=0;i<l;i++)
{
sd.append(c[i]);
}
str=sd.toString();
return str;
}
public static void main(String[] ar)
{
RemoveDup obj=new RemoveDup();
Scanner sc=new Scanner(System.in);
String st,t;
System.out.println("enter name:");
st=sc.nextLine();
sc.close();
t=obj.dup(st);
System.out.println(t);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication26;
import java.util.*;
/**
*
* #author THENNARASU
*/
public class JavaApplication26 {
public static void main(String[] args) {
int i,j,k=0,count=0,m;
char a[]=new char[10];
char b[]=new char[10];
Scanner ob=new Scanner(System.in);
String str;
str=ob.next();
a=str.toCharArray();
int c=str.length();
for(j=0;j<c;j++)
{
for(i=0;i<j;i++)
{
if(a[i]==a[j])
{
count=1;
}
}
if(count==0)
{
b[k++]=a[i];
}
count=0;
}
for(m=0;b[m]!='\0';m++)
{
System.out.println(b[m]);
}
}
}
i wrote this program. Am using 2 char arrays instead. You can define the number of duplicate chars you want to eliminate from the original string and also shows the number of occurances of each character in the string.
public String removeMultipleOcuranceOfChar(String string, int numberOfChars){
char[] word1 = string.toCharArray();
char[] word2 = string.toCharArray();
int count=0;
StringBuilder builderNoDups = new StringBuilder();
StringBuilder builderDups = new StringBuilder();
for(char x: word1){
for(char y : word2){
if (x==y){
count++;
}//end if
}//end inner loop
System.out.println(x + " occurance: " + count );
if (count ==numberOfChars){
builderNoDups.append(x);
}else{
builderDups.append(x);
}//end if else
count = 0;
}//end outer loop
return String.format("Number of identical chars to be in or out of input string: "
+ "%d\nOriginal word: %s\nWith only %d identical chars: %s\n"
+ "without %d identical chars: %s",
numberOfChars,string,numberOfChars, builderNoDups.toString(),numberOfChars,builderDups.toString());
}
Try this simple solution for REMOVING DUPLICATE CHARACTERS/LETTERS FROM GIVEN STRING
import java.util.Scanner;
public class RemoveDuplicateLetters {
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
System.out.println("enter a String:");
String s=scn.nextLine();
String ans="";
while(s.length()>0)
{
char ch = s.charAt(0);
ans+= ch;
s = s.replace(ch+"",""); //Replacing all occurrence of the current character by a spaces
}
System.out.println("after removing all duplicate letters:"+ans);
}
}
In Java 8 we can do that using
private void removeduplicatecharactersfromstring() {
String myString = "aabcd eeffff ghjkjkl";
StringBuilder builder = new StringBuilder();
Arrays.asList(myString.split(" "))
.forEach(s -> {
builder.append(Stream.of(s.split(""))
.distinct().collect(Collectors.joining()).concat(" "));
});
System.out.println(builder); // abcd ef ghjkl
}

how can i calculate the number of specific chars in a string?

Given a string how can i figure out the number of times each char in a string repeats itself
ex: aaaabbaaDD
output: 4a2b2a2D
public static void Calc() {
Input();
int count = 1;
String compressed = "";
for (int i = 0; i < input.length(); i++) {
if (lastChar == input.charAt(i)) {
count++;
compressed += Integer.toString(count) + input.charAt(i);
}
else {
lastChar = input.charAt(i);
count = 1;
}
}
System.out.println(compressed);
}
What you'r looking for is "Run-length encoding". Here is the working code to do that;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RunLengthEncoding {
public static String encode(String source) {
StringBuffer dest = new StringBuffer();
// iterate through input string
// Iterate the string N no.of.times where N is size of the string to find run length for each character
for (int i = 0; i < source.length(); i++) {
// By default run Length for all character is one
int runLength = 1;
// Loop condition will break when it finds next character is different from previous character.
while (i+1 < source.length() && source.charAt(i) == source.charAt(i+1)) {
runLength++;
i++;
}
dest.append(runLength);
dest.append(source.charAt(i));
}
return dest.toString();
}
public static String decode(String source) {
StringBuffer dest = new StringBuffer();
Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z]");
Matcher matcher = pattern.matcher(source);
while (matcher.find()) {
int number = Integer.parseInt(matcher.group());
matcher.find();
while (number-- != 0) {
dest.append(matcher.group());
}
}
return dest.toString();
}
public static void main(String[] args) {
String example = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
System.out.println(encode(example));
System.out.println(decode("1W1B1W1B1W1B1W1B1W1B1W1B1W1B"));
}
}
This program first finds the unique characters or numbers in a string. It will then check the frequency of occurance.
This program considers capital and small case as different characters. You can modify it if required by using ignorecase method.
import java.io.*;
public class RunLength {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
System.out.println("Please enter the string");
String str = br.readLine();//the input string is in str
calculateFrequency(str);
}
private static void calculateFrequency(String str) {
int length = str.length();
String characters[] = new String[length];//to store all unique characters in string
int frequency[] = new int[length];//to store the frequency of the characters
for (int i = 0; i < length; i++) {
characters[i] = null;
frequency[i] = 0;
}
//To get unique characters
char temp;
String temporary;
int uniqueCount = 0;
for (int i = 0; i < length; i++) {
int flag = 0;
temp = str.charAt(i);
temporary = "" + temp;
for (int j = 0; j < length; j++) {
if (characters[j] != null && characters[j].equals(temporary)) {
flag = 1;
break;
}
}
if (flag == 0) {
characters[uniqueCount] = temporary;
uniqueCount++;
}
}
// To get the frequency of the characters
for(int i=0;i<length;i++){
temp=str.charAt(i);
temporary = ""+temp;
for(int j=0;i<characters.length;j++){
if(characters[j].equals(temporary)){
frequency[j]++;
break;
}
}
}
// To display the output
for (int i = 0; i < length; i++) {
if (characters[i] != null) {
System.out.println(characters[i]+" "+frequency[i]);
}
}
}}
Some hints: In your code sample you also need to reset count to 0 when the run ends (when you update lastChar). And you need to output the final run (after the loop is done). And you need some kind of else or continue between the two cases.
#Balarmurugan k's solution is better - but just by improving upon your code I came up with this -
String input = "aaaabbaaDD";
int count = 0;
char lastChar = 0;
int inputSize = input.length();
String output = "";
for (int i = 0; i < inputSize; i++) {
if (i == 0) {
lastChar = input.charAt(i);
count++;
} else {
if (lastChar == input.charAt(i)) {
count++;
} else {
output = output + count + "" + lastChar;
count = 1;
lastChar = input.charAt(i);
}
}
}
output = output + count + "" + lastChar;
System.out.println(output);

Categories