I need to replace a repeated char with $% followed by the char followed by $%.
e.g. "HELLO" will become "HE$%L$%O"
The following code that I wrote gives "HE$%L$%LO".
Please guide
int index=0;
String str1="";
String str2="";
String str4="";
String str5="";
for(int i=0;i<str.length();i++) {
char ch=str.charAt(i);
index=str.indexOf(ch);
if(index!=i) {
str4="$%"+str.charAt(index)+ "$%";
str1=str.charAt(index)+str5;
str2=str.replaceFirst(str1,str4);
}
}
return str2;
It looks like there's code missing because i can't see the duplicate character check, but what you want to do is go through str5 before you concat it and strip off all of the duplicate characters that are at the beginning. Then concat to your String.
Here a solution: Id solves the case if duplicates are more than 2 too. So remove all duplicates:
public class Converter {
public static void main(String[] args) {
final String result = replace("HELLO");
System.out.println("result = " + result);
}
private static String replace(String data) {
final StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < data.length();) {
int j = i + 1;
while (j < data.length() && data.charAt(i) == data.charAt(j)) {
j++;
}
if(j > i + 1) { // exist duplicate
stringBuilder.append("$%").append(data.charAt(i)).append("$%");
} else {
stringBuilder.append(data.charAt(i));
}
i = j;
}
return stringBuilder.toString();
}
}
And the result is:
result = HE$%L$%O
Related
here it is giving error----required variable ,found value
my code
for eg aabacc when we got any pair like aa remove it from string and the final answer is (ba).
public class Solution {
// Complete the superReducedString function below.
static String superReducedString(String s) {
String sn;
int j=0;
for(int i=0;i<s.length()-1;i++)
{
if(s.charAt(i)!=s.charAt(i+1))
{
sn.charAt(j)=s.charAt(i);
j++;
}
}
return sn;
}
Since String is immutable in Java - String manipulation always generates a new String leaving the previous Strings in String Pool. StringBuffer and StringBuilder are mutable objects and provide methods for String manipulation
Sample working method using StringBuilder is provided below:
static String superReducedString(String s) {
StringBuilder myName = new StringBuilder(s);
int j=0;
for(int i=0;i<s.length()-1;i++) {
if(s.charAt(i)!=s.charAt(i+1)) {
myName.setCharAt(j, s.charAt(i));
j++;
}
}
return myName.toString();
}
You can not do such assignment like sn.charAt(j)=s.charAt(i); since charAt() is function that returns the result, but not a variable. You could use StringBuilder here:
static String superReducedString(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (s.length() == i+1 || s.charAt(i) != s.charAt(i + 1)) {
sb.append(s.charAt(i));
} else {
i++;
}
}
return sb.toString();
}
s.length() == i+1 checks if it's the last char. In case aabaccr the result will be as expected bar
Just another solution, in case the other answers don't work for you:
static String superReducedString(String s) {
char[] chars = s.toCharArray();
String lastChar = "";
ArrayList<String> newString = new ArrayList<>();
for (char aChar : chars) {
String currentChar = String.valueOf(aChar);
if (lastChar.equals(currentChar))
newString.remove(newString.size() - 1);
else {
newString.add(currentChar);
lastChar = currentChar;
}
}
AtomicReference<String> returnString = new AtomicReference<>("");
newString.forEach(character-> returnString.set(returnString + character));
return returnString.get();
}
The answer is quite simple.
you cannot delete anything from a String but you can move them to another String as you want.
public class Solution {
public static void main(String[] args) {
String s = "abbccd", s1 = "";
if(s.charAt(1) != s.charAt(0))
s1 += s.charAt(0);
if(s.charAt(s.length()-1) != s.charAt(s.length()-2))
s1 += s.charAt(s.length()-1);
for (int i = 1; i < s.length() - 1; i++) {
if (s.charAt(i) != s.charAt(i - 1) && s.charAt(i) != s.charAt(i + 1))
s1 += s.charAt(i);
}
System.out.println(s1);
}
}
You create another String.
Then in a for loop iterating from 1 (NOT 0) to s.length()-1 (NOT s.length()), you check if the s.charAt(i) (current character) is equal to the preceding or following one. If it's not equal to any of them, you add it to the second String and then you print it. We are checking both sides so that's why the loop is from 1 to s.length()-1, to avoid out of bounds exceptions.
EDIT: to check the first and last character.
This is my method. It doesn't return anything. Please help, I don't know how to get the desired String name longer (the initial word string with hyphens between characters). `
public static String stretch(String word){
String longer = "" + word.charAt(0);
for (int i=1; i<=word.length()-1; i++){
longer += "-" + word.charAt(i);
}
return longer;
}
Below are three different ways of achieving your desired result, they are in ascending order in terms of performance + simplicity to understand i.e. stretch3 > stretch2 > stretch1.
import java.util.StringJoiner;
class Main {
public static void main(String[] args) {
System.out.println(stretch("test"));
System.out.println(stretch2("test"));
System.out.println(stretch3("test"));
}
// Using String Concatenation (bad)
public static String stretch(String word) {
String longer = "" + word.charAt(0);
for (int i = 1; i < word.length(); i++) {
longer += "-" + word.charAt(i);
}
return longer;
}
// Using StringBuilder (good)
public static String stretch2(String word) {
StringBuilder longer = new StringBuilder(word.substring(0,1));
for (int i = 1; i < word.length(); i++) {
longer.append("-" + word.charAt(i));
}
return longer.toString();
}
// Using StringJoiner (best)
public static String stretch3(String word) {
StringJoiner longer = new StringJoiner("-");
for (int i = 0; i < word.length(); i++) {
longer.add(word.substring(i,i+1));
}
return longer.toString();
}
}
Output:
t-e-s-t
t-e-s-t
t-e-s-t
Try it here!
Try if you want to insert a hyphen between letters (and not words)
"test sample".replaceAll("\\w(?=\\w)", "$0-");
Output -> t-e-s-t s-a-m-p-l-e
I'm making a method
public static String merge(String... s)
This is the input:
String a = merge("AM ","L","GEDS","ORATKRR","","R TRTE","IO","TGAUU");
System.out.println(a);
Expected Output:
ALGORITMER OG DATASTRUKTURER
I try to run a loop many times so that it picks up s[0].charAt(index) and appends it to a string for output. The problem I run into is that when I try to run the loop for s[1].charAt(1) it's null, I want it to not get StringIndexOutOfBoundsException, and instead continue to s[2] and appends s[2].char to the String.
How do I go about that?
You need to check the length of each String before trying to access its i'th character :
StringBuilder sb = new StringBuilder();
int index = 0;
boolean maxLengthReached = false;
while (!maxLengthReached) {
maxLengthReached = true;
for (String str : input) {
if (index < str.length) {
sb.append(str.charAt(index));
maxLengthReached = false;
}
}
index++;
}
return sb.toString();
Just to clarify, I'm using a boolean maxLengthReached to determine when the last character of the longest String is appended to the output. If in a full iteration over all the Strings in the input array we don't find any String long enough to have charAt(index), we know we are done.
First you need a method to get the longest String, something like -
private static String getLongestString(String... arr) {
String str = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i].length() > str.length()) {
str = arr[i];
}
}
return str;
}
Then you can write a nested loop in your merge(), something like -
public static String merge(String... stringArray) {
StringBuilder sb = new StringBuilder();
int pos = 0;
int len = getLongestString(stringArray).length();
while (pos < len) {
for (String str : stringArray) {
if (str.length() > pos) {
sb.append(str.charAt(pos));
}
}
pos++;
}
return sb.toString();
}
Then you can call it -
public static void main(String[] args) {
String a = merge("AM ", "L", "GEDS", "ORATKRR", "", "R TRTE", "IO",
"TGAUU");
System.out.println(a);
}
Output is (the requested) -
ALGORITMER OG DATASTRUKTURER
The following code does what you need. It works for any number of strings because it uses the varargs (three dots) that allow you to pass any number of strings into merge
Use the getLongest() to find the length of the longest string.
static int getLongest(String... strings) {
int len = 0;
for(String str : strings) {
if(str.length() > len) {
len = str.length();
}
}
return len;
}
Then you merge all the i-th character from each String into a StringBuilder.
static String merge(String ...strings) {
int longest = getLongest(strings);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < longest; i++) {
for(String str : strings) {
if(i < str.length()) {
sb.append(str.charAt(i));
}
}
}
return sb.toString();
}
public static void main(String[] args) {
String a = merge("AM ","L","GEDS","ORATKRR","","R TRTE","IO","TGAUU");
System.out.println(a);
}
Output
ALGORITMER OG DATASTRUKTURER
I need to write a static method that takes a String as a parameter and returns a new String obtained by replacing every instance of repeated adjacent letters with a single instance of that letter without using regular expressions. For example if I enter "maaaakkee" as a String, it returns "make".
I already tried the following code, but it doesn't seem to display the last character.
Here's my code:
import java.util.Scanner;
public class undouble {
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.println("enter String: ");
String str = console.nextLine();
System.out.println(removeSpaces(str));
}
public static String removeSpaces(String str){
String ourString="";
int j = 0;
for (int i=0; i<str.length()-1 ; i++){
j = i+1;
if(str.charAt(i)!=str.charAt(j)){
ourString+=str.charAt(i);
}
}
return ourString;
}
}
You could use regular expressions for that.
For instance:
String input = "ddooooonnneeeeee";
System.out.println(input.replaceAll("(.)\\1{1,}", "$1"));
Output:
done
Pattern explanation:
"(.)\\1{1,}" means any character (added to group 1) followed by itself at least once
"$1" references contents of group 1
maybe:
for (int i=1; i<str.length() ; i++){
j = i+1;
if(str.charAt(i)!=str.charAt(j)){
ourString+=str.charAt(i);
}
}
The problem is with your condition. You say compare i and i+1 in each iteration and in last iteration you have both i and j pointing to same location so it will never print the last character. Try this unleass you want to use regex to achive this:
EDIT:
public void removeSpaces(String str){
String ourString="";
for (int i=0; i<str.length()-1 ; i++){
if(i==0){
ourString = ""+str.charAt(i);
}else{
if(str.charAt(i-1) != str.charAt(i)){
ourString = ourString +str.charAt(i);
}
}
}
System.out.println(ourString);
}
if you cannot use replace or replaceAll, here is an alternative. O(2n), O(N) for stockage and O(N) for creating the string. It removes all repeated chars in the string put them in a stringbuilder.
input : abcdef , output : abcdef
input : aabbcdeef, output : cdf
private static String remove_repeated_char(String str)
{
StringBuilder result = new StringBuilder();
HashMap<Character, Integer> items = new HashMap<>();
for (int i = 0; i < str.length(); i++)
{
Character current = str.charAt(i);
Integer ocurrence = items.get(current);
if (ocurrence == null)
items.put(current, 1);
else
items.put(current, ocurrence + 1);
}
for (int i = 0; i < str.length(); i++)
{
Character current = str.charAt(i);
Integer ocurrence = items.get(current);
if (ocurrence == 1)
result.append(current);
}
return result.toString();
}
import java.util.*;
public class string2 {
public static void main(String[] args) {
//removes repeat character from array
Scanner sc=new Scanner(System.in);
StringBuffer sf=new StringBuffer();
System.out.println("enter a string");
sf.append(sc.nextLine());
System.out.println("string="+sf);
int i=0;
while( i<sf.length())
{
int j=1+i;
while(j<sf.length())
{
if(sf.charAt(i)==sf.charAt(j))
{
sf.deleteCharAt(j);
}
else
{
j=j+1;
}
}
i=i+1;
}
System.out.println("string="+sf);
}
}
Input AABBBccDDD, Output BD
Input ABBCDDA, Outout C
private String reducedString(String s){
char[] arr = s.toCharArray();
String newString = "";
Map<Character,Integer> map = new HashMap<Character,Integer>();
map.put(arr[0],1);
for(int index=1;index<s.length();index++)
{
Character key = arr[index];
int value;
if(map.get(key) ==null)
{
value =0;
}
else
{
value = map.get(key);
}
value = value+1;
map.put(key,value);
}
Set<Character> keyset = map.keySet();
for(Character c: keyset)
{
int value = map.get(c);
if(value%2 !=0)
{
newString+=c;
}
}
newString = newString.equals("")?"Empty String":newString;
return newString;
}
public class RemoveDuplicateCharecterInString {
static String input = new String("abbbbbbbbbbbbbbbbccccd");
static String output = "";
public static void main(String[] args)
{
// TODO Auto-generated method stub
for (int i = 0; i < input.length(); i++) {
char temp = input.charAt(i);
boolean check = false;
for (int j = 0; j < output.length(); j++) {
if (output.charAt(j) == input.charAt(i)) {
check = true;
}
}
if (!check) {
output = output + input.charAt(i);
}
}
System.out.println(" " + output);
}
}
Answer : abcd
public class RepeatedChar {
public static void main(String[] args) {
String rS = "maaaakkee";
String outCome= rS.charAt(0)+"";
int count =0;
char [] cA =rS.toCharArray();
for(int i =0; i+1<cA.length; ++i) {
if(rS.charAt(i) != rS.charAt(i+1)) {
outCome += rS.charAt(i+1);
}
}
System.out.println(outCome);
}
}
TO WRITE JAVA PROGRAM TO REMOVE REPEATED CHARACTERS:
package replace;
public class removingrepeatedcharacters
{
public static void main(String...args){
int i,j=0,count=0;
String str="noordeen";
String str2="noordeen";
char[] ch=str.toCharArray();
for(i=0;i<=5;i++)
{
count=0;
for(j=0;j<str2.length();j++)
{
if(ch[i]==str2.charAt(j))
{
count++;
System.out.println("at the index "+j +"position "+ch[i]+ "+ count is"+count);
if(count>=2){
str=str2;
str2=str.replaceFirst(Character.toString(ch[j]),Character.toString(' '));
}
System.out.println("after replacing " +str2);
}
}
}
}
}
String outstr = "";
String outstring = "";
for(int i = 0; i < str.length() - 1; i++) {
if(str.charAt(i) != str.charAt(i + 1)) {
outstr = outstr + str.charAt(i);
}
outstring = outstr + str.charAt(i);
}
System.out.println(outstring);
public static void remove_duplicates(String str){
String outstr="";
String outstring="";
for(int i=0;i<str.length()-1;i++) {
if(str.charAt(i)!=str.charAt(i+1)) {
outstr=outstr+str.charAt(i);
}
outstring=outstr+str.charAt(i);
}
System.out.println(outstring);
}
More fun with java 7:
System.out.println("11223344445555".replaceAll("(?<nums>.+)\\k<nums>+","${nums}"));
No more cryptic numbers in regexes.
public static String removeDuplicates(String str) {
String str2 = "" + str.charAt(0);
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i - 1) == str.charAt(i) && i != 0) {
continue;
}
str2 = str2 + str.charAt(i);
}
return str2;
}
I'm trying to write a code that will give this output:
plusOut("12xy34", "xy") → "++xy++"
it returns a string where the characters in the original have been replaced by + except for where the 2nd string appears in the first string, but im having problems with my code. Here it is:
public String plusOut(String str, String word) {
String newString = "";
for (int i=0; i<str.length()-1; i++) {
if (str.substring(i, word.length()).equals(word)) {
newString = newString + str.substring(i, word.length());
}
else {
newString = newString + "+";
}
}
return newString;
}
There are some bugs in your code, see the comments.
public String plusOut(String str, String word) {
String newString = "";
// iterate up to length() to catch the last char if word.length() is 1
for (int i = 0; i < str.length(); i++) {
// use min() to avoid an IndexOutOfRange
String sub = str.substring(i, Math.min(i+word.length(), str.length()));
if (sub.equals(word)) {
newString = newString + sub;
// skip remaining characters of word
i += sub.length()-1;
}
else {
newString = newString + "+";
}
}
return newString;
}
In addition to that, I'd use a StringBuilder instead of the + operator.
You should really tell us what specific problems you are facing with your current code. In any case, here's how I would do it:
Split str on all occurrences of word to form a String[].
Loop through this array and append a number of '+' characters to newString corresponding to the length of whatever element of the array you're on.
On the same loop iteration, append word to newString, unless of course you're on the last element of the array.
This is what I mean:
public static String plusOut(String str, String word) {
StringBuilder newString = new StringBuilder(str.length());
String[] split = str.split(word);
for (int i = 0; i < split.length; i++) {
for (int j = 0; j < split[i].length(); j++)
newString.append('+');
if (i != split.length - 1)
newString.append(word);
}
return newString.toString();
}
Oh and just another tip: try to avoid appending to strings repeatedly within a loop. If you need to, use a StringBuilder instead.
System.out.println(plusOut("12xy34", "xy"));
++xy++
The best and simplest way I can think of is to use regular expressions and do a replaceAll.
General idea will be to get the second character build an regex with that and replaceAll with the regular expression and the replacement character.
public String plusOut(String str, String word) {
String regEx="[^"+Pattern.quote(word)+"]";
str.replaceAll(regEx,"+");
}
Note that the Pattern.quote() will make sure that your word won't screw the regex.
I didn't try out the code, but it should work without a problem.
This will do that for you.
public String plusOut(String str, String word) {
if(!str.contains(word)){
System.out.println("Word not found in string!");
return "Ut-oh!";
}
int indexOfStart = str.indexOf(word);
StringBuilder sb = new StringBuilder();
for(int i = 0; i<indexOfStart; i++){
sb.append('+');
}
sb.append(word);
for(int i=indexOfStart+word.length(); i < str.length(); i++){
sb.append('+');
}
return sb.toString();
}
So many answers! Well, here's mine as well:
public static String plusOut(String str, String word) {
String output = "";
int index = str.indexOf(word); // if -1 is returned, replace all chars
for (int i= 0; i < str.length(); i++) {
if(i == index)
{
output += word;
i += word.length() -1; // because i++ will still occurr
continue;
}
output += "+";
}
return output;
}
and test code in main:
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String test = "somethinghello12345.1!#";
System.out.println(test + " -> " + plusOut(test, "hello"));
test = "somethinghello12345.1!#";
System.out.println(test + " -> " + plusOut(test, "not gonna work"));
}
will produce the ouput:
somethinghello12345.1!# -> +++++++++hello+++++++++
somethinghello12345.1!# -> +++++++++++++++++++++++
Try this :
public static String plusOut(String word, String find) {
StringBuilder newStr = new StringBuilder();
int start = word.indexOf(find);
if (start > -1) {
for (int i = 0; i < start; i++) {
newStr.append("+");
}
newStr.append(find);
for (int i = 0; i < word.length() - (start + find.length()); i++) {
newStr.append("+");
}
}
return newStr;
}