I have the below String variable
String s = "abc,xyz,lmn,ijk";
I want to extract only the portion of the String (i.e - 'lmn')
And, Should not use in-built functions like, SubString(), Split(), IndexOf(). But I can use charArray()
And this question was asked in my interview.
I tried the below code,
But not sure how to proceed. Can any one please provide your thoughts?
String s = "abc,xyz,lmn,ijk";
int counter = 0;
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (ch[i] == ',') {
counter++;
}
}
Here's one way:
public static void main(String[] args) {
String s = "abc,xyz,lmn,ijk";
char[] ch = s.toCharArray();
int counter = 0;
int place = 2;
for (int i = 0; i < ch.length-2; i++) {
if(ch[i] == ',') {
counter++;
}
if(counter == place && ch[i] != ',') {
System.out.print(ch[i]);
}
}
}
It prints everything after the second comma, but before the third one.
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "abc,xyz,lmn,ijk";
StringBuffer sb=new StringBuffer();
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if(','==(ch[i]))
{
if (sb.toString().equals("lmn")) {
System.out.println(sb.toString());
}
else
{
int length=sb.length();
sb.delete(0, length);
}
}
else
{
sb.append(ch[i]);
}
}
}
I would do it this way.
String s = "abc,xyz,lmn,ijk";
String x = "c,x"; // String to found
String r = "";
boolean coincidence = false;
int a=0; // Initial index if of the first character in x is found
int b=0; // Last index If it was possible to search for the last character of x
int c=0; // Index "iterator" on String x
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if(c == x.length())
break;
else{
if(ch[i] == x.charAt(c) && !coincidence){
a = i; b = i; c++;
coincidence = true;
}
else if(ch[i] == x.charAt(c) && coincidence){
b++; c++;
}else{
coincidence = false;
a = 0; b = 0; c = 0;
}
}
}
System.out.println("String: " + s);
System.out.println("String to find: " + x);
System.out.println("Was found? " + ((coincidence)? "Yes" : "No"));
if(coincidence){
System.out.println("Intervals indexes in String: ["+a + "," + b +"]");
// String extration
for (int i = a; i <= b; i++)
r += s.charAt(i);
System.out.println("String extracted: " + r);
}
Related
I want to only remove 'a' in " brealdeke "
This program works, it prints " breldeke " but if I were to put
" brealdeake" with 2 'a' in this string, it goes berserk and prints : breldeakebrealdeke How to fix it ? Thanks
I really want it to look this this :
class Example {
public static String suppression(char c, String s) {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c) {
int position = i;
for (int a = 0; a < position; a++) {
System.out.print(s.charAt(a));
}
for (int b = position + 1; b < s.length(); b++) {
System.out.print(s.charAt(b));
}
}
}
return "";
}
public static void main(String[] args) {
// prints "breldeke"
System.out.println(suppression('a', "brealdeke"));
// prints "breldeakebrealdeke"
System.out.print(suppression('a', "brealdeake"));
}
}
You could try :
"banana".replaceFirst("a", "");
This returns bnana
EDIT: Hopefully, this doesn't include anything you haven't been taught yet
public static void main(String[] args) {
String word = "banana";
String strippedWord = "";
boolean found = false;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == 'a' && !found) found = !found;
else strippedWord += word.charAt(i);
}
System.out.println(strippedWord);
}
This prints bnana
EDIT2 : You said you wanted it in a function, the same applies :
public static String suppression(char c, String word) {
String strippedWord = "";
boolean charRemoved = false; // This is a boolean variable used to know when the char was skipped!
for (int i = 0; i < word.length(); i++) {
// If the current letter is for example 'a' and we haven't yet skipped the char, skip this char we're at
if (word.charAt(i) == c && charRemoved == false) charRemoved = true;
else strippedWord += word.charAt(i);
}
return strippedWord;
}
public static void main(String[] args) {
// prints "breldeke"
System.out.println(suppression('a', "brealdeke"));
// prints "breldeake"
System.out.print(suppression('a', "brealdeake"));
}
Additional variables OK?
I'd do it like this personally:
public static String removeFirstLetter(string s, char c)
{
String word = "";
Bool foundChar = false;
for ( int i = 0; i<s.length();i++) {
if (s.charAt(i).toLower() != c)
{
word += s.char(i);
}
else
{
if (foundChar == false){
foundChar = true;
}
else
{
word += s.char(i);
}
}
}
}
System.out.print(word);
Using java, input string="aabbcdeaaaabbb" and the output must be aaaa, as sequence here is having repeated 4 times a. Can anyone help me to get this "aaaa" as output using java implementation.
Algorithm to find the Longest substring having same character repeated.
for eg:
I/P: aabbcdefaaaacccccc O/P: cccccc
Please check my program below and suggest any optimization for faster processing:
public class LongestSubString {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
System.out
.println("Enter a word to find longest substring with same characters repeated");
String word = reader.readLine();
System.out.println("Entered word is: " + word);
System.out.println("Longest repeated characters substring is: "
+ subStringFinder(word));
}
/*
*longest substring finder with same character repeated
*/
public static String subStringFinder(String word) {
char[] tokens = word.toCharArray();
int len = tokens.length;
int wordLen = word.length();
System.out.println("len of input word: " + wordLen);
List<String> myList = new ArrayList<>();
StringBuilder strConcat = new StringBuilder("");
for (int j = 0; j <= len - 1; j++) {
if (j + 1 > len - 1) {
if ((strConcat.length() >= 1)
&& (strConcat.charAt(strConcat.length() - 1) == (tokens[j]))) {
strConcat.append("" + tokens[j]);
myList.add(strConcat.toString());
}
}
else {
if (tokens[j] == tokens[j + 1]) {
if ((strConcat.length() >= 1)
&& (strConcat.charAt(strConcat.length() - 1) == (tokens[j]))) {
strConcat.append("" + tokens[j]);
myList.add(strConcat.toString());
} else {
strConcat = new StringBuilder("");
strConcat.append("" + tokens[j]);
}
} else {
if ((strConcat.length() >= 1)
&& (strConcat.charAt(strConcat.length() - 1) == (tokens[j]))) {
strConcat.append("" + tokens[j]);
myList.add(strConcat.toString());
} else {
strConcat = new StringBuilder("");
strConcat.append("" + tokens[j]);
}
}
}
}
int max = 0, index = 0;
for (int i = 0; i < myList.size(); i++) {
String strEle = myList.get(i);
int strLen = strEle.length();
if (max < strLen) {
max = strLen;
index = i;
}
}
return myList.get(index);
}
}
I believe your code is overly complicated. You don’t need a StringBuilder nor an ArrayList. I tried to understand your intention, but then skipped it and wrote my own version instead. Hope it helps anyway.
public static String subStringFinder(String word) {
if (word == null || word.isEmpty()) {
return word;
}
char currentChar = word.charAt(0);
int longestStart = 0;
int longestLength = 0;
int currentStart = 0;
int currentLength = 1;
for (int ix = 1; ix < word.length(); ix++) {
if (word.charAt(ix) == currentChar) {
currentLength++;
} else {
if (currentLength > longestLength) {
longestStart = currentStart;
longestLength = currentLength;
}
currentChar = word.charAt(ix);
currentStart = ix;
currentLength = 1;
}
}
if (currentLength > longestLength) {
longestStart = currentStart;
longestLength = currentLength;
}
return word.substring(longestStart, longestStart + longestLength);
}
String in = "aabbcdeaaaabbb";
String t;
ArrayList<String> out = new ArrayList<String>();
String l="";
int c=0;
String n;
for(int i=0;i<in.length;i++) {
n=in.substring(i, i+1); //get the current character
if(n.equals(l)){
l=n; c++;
}
else {
t=n;
for(int j=1;j<c;j++) {
n+=t;
}
c=0;
out.add(n);
c=0;
}
}
I want to shift each i in a given string one index to the right. How can I do that? For example:
"Chit Nyein Oo is nothing.";
becomes
"Chti Nyeni Oo si nothnig.";
If i occurs in the last index, it need not change its position.
Use string.replaceAll
string.replaceAll("i(.)", "$1i");
DEMO
EDIT: NOW it works for all conditions. Last letter in the String is 'i' or not, it works.
public class t4 {
public static void main(String[] args) {
String input = "Chit Nyein Oo is nothing.";
char o = 'i';
int indexes = 0;
if(input.charAt(input.length()-1) != 'i'){ //Test if last letter is not 'i'
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == o){
indexes++;
}
}
int []positions = new int[indexes];
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == o){
positions[indexes-1] = i;
indexes--;
}
}
char[] characters = input.toCharArray();
for (int i = 0; i < positions.length; i++) {
if(characters[input.length()-1] != 'i'){
char temp = characters[positions[i]];
characters[positions[i]] = characters[positions[i]+1];
characters[positions[i]+1] = temp;
} else {
continue;
}
}
String swappedString = new String(characters);
System.out.println(input);
System.out.println(swappedString);
} else { //so last letter is i
char t = input.charAt(input.length()-1);
String ha = input.substring(0, input.length()-1);
input = ha;
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == o){
indexes++;
}
}
int []positions = new int[indexes];
for (int i = 0; i < input.length(); i++) {
if(input.charAt(i) == o){
positions[indexes-1] = i;
indexes--;
}
}
char[] characters = input.toCharArray();
for (int i = 0; i < positions.length; i++) {
if(characters[input.length()-1] != 'i'){
char temp = characters[positions[i]];
characters[positions[i]] = characters[positions[i]+1];
characters[positions[i]+1] = temp;
} else {
continue;
}
}
String swappedString = new String(characters);
swappedString = swappedString + Character.toString(t);
System.out.println(input);
System.out.println(swappedString);
}
}
}
You can do this using a StringBuilder.
class Test {
public static void main(String[] args) {
String input = "Chit Nyein Oo is nothingi";
int len = input.length();
StringBuilder sb = new StringBuilder();
// System.out.println(sb);
for(int i=0; i<len; i++) {
char charAti = input.charAt(i);
if(charAti == 'i' && i<len-1) {
sb.append(input.charAt(i+1));
sb.append(charAti);
i++;
}
else {
sb.append(charAti);
}
}
System.out.println(sb);
}
}
I'm trying to get a head start on practicing interview questions and I came across this one:
Turn String aaaabbbbddd into a4b4d3
You would basically want to convert the existing string into a string with each unique character occurrence and the number of times the character occurs.
This is my solution but I think it could be refined into something more elegant:
String s = "aaaabbbbddd";
String modified = "";
int len = s.length();
char[] c = s.toCharArray();
int count = 0;
for (int i = 0; i < len; i++) {
count = 1;
for (int j = i + 1; j < len; j++) {
if (c[i] == ' ') {
break;
}
if (c[i] == c[j]) {
count++;
c[j] = ' ';
}
}
if (c[i] != ' ') {
modified += c[i] + "" + count;
}
}
System.out.println(modified);
Does anyone have any other suggestions for a solution?
Employ a Map<Character, Integer> instead. Attempt to insert the new character into the map; if it already exists, then increment the value for that particular character.
Example:
Map<Character, Integer> countMap = new HashMap<>();
if(!countMap.containsKey('a')) {
countMap.put('a', 1);
} else {
countMap.put('a', countMap.get('a') + 1);
}
To add on to #Makoto's wonderful answer, in your situation, I would use a TreeMap instead of a HashMap. A TreeMap will allow you to print in alphabetical order. I have also added the print code to show you how it would look. It's fully runnable.
import java.util.Map;
import java.util.TreeMap;
public class MapPractice {
public static void main(String[] args) {
Map<Character, Integer> map = new TreeMap<>();
String blah = "aaaabbbbddd";
for (int i = 0; i < blah.length(); i++) {
char c = blah.charAt(i);
if (!map.containsKey(c)) {
map.put(c, 1);
} else {
map.put(c, (map.get(c) + 1));
}
}
for (Map.Entry<Character, Integer> entry: map.entrySet()) {
System.out.print(entry.getKey() + "" + entry.getValue());
}
}
}
Output with TreeMap: a4b4d3
Output with HashMap: d3b4a4
My version
StringBuilder sb = new StringBuilder();
int count = 0;
char last = s.charAt(0);
for(char c : s.toCharArray()) {
if (c == last) {
count++;
} else {
sb.append(last).append(count);
count = 0;
last = c;
}
}
if (count != 0) {
sb.append(last).append(count);
}
System.out.println(sb);
Here is the code that I tried.
I think you can't ask for a simpler code than this.
String s = "aaaabbbbddd", modified = "";
int len = s.length(), i = 0, j = i + 1, count = 1;
char[] c = s.toCharArray();
for (; i < len; i = j) {
count = 1;
for (; j < len; j++)
if (c[i] == c[j])
count++;
else {
j++;
break;
}
modified += c[i] + "" + count;
}
System.out.println(modified);
Hope you find this useful.
Method 1
Scanner scan = new Scanner(System.in);
System.out.print("Enter the string : ");
String str = scan.nextLine();
char c;
char[] charArr = str.toCharArray();
LinkedHashMap<Character,Integer> map = new LinkedHashMap<>();
for(int i = 0 ; i < charArr.length ; i++)
{
c = charArr[i];
if(map.containsKey(c) || map.containsKey(c-32))
{
if(c<97)
{
map.put(c,map.get(c)+1);
}
else
{
map.put(c,map.get(c)+1);
}
}
else
{
map.put((char)(c+32),1);
}
}
for(Map.Entry e : map.entrySet())
{
System.out.print(""+e.getKey()+""+e.getValue());
}
Method 2
Scanner scan = new Scanner(System.in);
System.out.print("Enter the string : ");
String str = scan.nextLine();
String newStr = "";
char c;
int count = 1;
char[] charArr = str.toCharArray();
for(int i = 0 ; i < charArr.length ; i++)
{
c = charArr[i];
if(i>0)
{
if ( c == charArr[i-1] || c == (char)(charArr[i-1]+32) )
{
count++;
}
else
{
if(c < 97)
{
newStr = newStr + count;
count = 1;
newStr = newStr + (char)(c+32);
}
else
{
newStr = newStr + count;
count = 1;
newStr = newStr + c;
}
}
}
else
{
if(c < 97)
{
newStr = newStr + (char)(c+32);
}
else
{
newStr = newStr + (char)c;
}
}
}
newStr = newStr + count;
System.out.print(newStr);
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner S=new Scanner(System.in);
String in=S.next();
int count=1;
String out="";
for(int i=0;i<in.length()-1;){
out+=in.charAt(i+1);
count=1;
if(in.charAt(i)!=in.charAt(i+1)){
out+=count;
i++;
}else{
while(i<in.length()-1){
if(in.charAt(i)==in.charAt(i+1)){
count++;
i++;
}
else{
i++;
break;
}
}
out+=count;
}
}
System.out.println(out);
}
}
Here is my solution
public String countChars(String in){
LinkedHashMapMap<Character, Integer> map = new LinkedHashMap<Character, Integer>();
for(char c: in.toCharArray()){
Integer count = map.get(c);
if(count==null){
count=0;
}
count++;
map.put(c,count);
}
String out ="";
for(Entry<Character, Integer> e : map.entrySet()){
out += e.getKey()+e.getValue();
}
return out;
}
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);