I am having difficulty in the following, replacing certain characters from the string
There will be two inputs, first will be character and second will be string
then I need to replace all those characters from the string with it's position
for example ,
the input and output of my program are as follows which is absolutely correct as per the requirement
Input : i this is Ignite
( Here "i" is the first input and "this is Ignite" is the second input
Output : th2s 5s 8gn11te
Input : i this is ignite and i am pratik
Output : th2s 5s 8gn11te and 20 am prat30k
The replacement should not be case-sensitive.
I had written the following program but it's having some bugs, Bugs in the sense that I am actually doing some project online and the automated sytem is not accepting the program because of some logical error.The automated system does some test cases with different inputs and check the output ( not exceptions or invalid inputs) can someone help me identify it ?
import java.util.*;
import java.io.*;
class rplc
{
public static void main(String args[])
{
String str,temp="";
char ch, ch2;
int arr[]=new int[100];
int len,i,x=0;
Scanner input=new Scanner(System.in);
ch=input.next().charAt(0);
str=input.nextLine();
str=str.replaceAll("^\\s+","");
ch2=ch;
if(Character.isUpperCase(ch))
ch2=Character.toLowerCase(ch);
else if(Character.isLowerCase(ch))
ch2=Character.toUpperCase(ch);
len=str.length();
temp=str;
for(i=0;i<len;i++)
{
if(str.charAt(i)==(int)ch || str.charAt(i)==(int)ch2)
{
arr[x]=i;
x=x+1;
}
}
x=0;
for(i=0;i<len;i++)
{
if(str.charAt(i)==(int)ch || str.charAt(i)==(int)ch2)
{
temp=str.substring(0,i);
temp=temp+(arr[x]);
temp=temp+str.substring(i+1,len);
str=temp;
len=temp.length();
x=x+1;
}
}
System.out.print(temp);
}
}
Seems like your code should work. Just in case I tried writing a simpler program:
Scanner input=new Scanner(System.in);
char ch = Character.toLowerCase(input.next().charAt(0));
String str = input.nextLine().trim().toLowerCase();
input.close();
StringBuffer buf = new StringBuffer();
for (int i = 0; i < str .length(); i++) {
if (str.charAt(i) == ch) {
buf.append(i);
}
else {
buf.append(str.charAt(i));
}
}
System.out.println(buf.toString());
And the output seems to be same.
Perhaps your function should return the value instead of printing it?
From the comments I understand that there will be only 1 input from the user.
The following input:
i this is ignite and i am pratik
Where the first 'i' is the charcter which needs to be replaced in 'this is ignite and i am pratik'.
Modify following:
str=input.nextLine();
str=str.replaceAll("^\\s+","");
to
str = input.nextLine();
str = str.substring(1);
str = str.replaceAll("^\\s+", "");
Try Something like this,
Scanner s = new Scanner(System.in);
String Line = s.nextLine();
String ch = Line.substring(0,Line.indexOf(" ")).trim();
Line = Line.substring(Line.indexOf(" ")).trim();
String[] x= Line.split(ch);
String y="";
for(String t:x){
y=y.equals("")?t:y+y.length()+t;
}
System.out.println(y);
I did some code cleaning but the most important steps were to use a list of dynamic size instead of a fixed size array and a while-loop with dynamic termination instead of a for-loop. This is because the length of the output String will change (increase) when there a characters to be replaced at positions >9 and thus in your code the execution can stop in the middle of the result string and there are characters not being replaced.
There is even a special case, when the replaced character is a number itself. To avoid problems there I added this line
i = i + Integer.toString(list.get(pos)).length()-1;
in order to step over newly added number characters in the output String.
import java.util.*;
import java.io.*;
class rplc
{
public static void main(String args[])
{
List<Integer> list = new ArrayList<Integer>();
Scanner input=new Scanner(System.in);
char ch = input.next().charAt(0);
String str=input.nextLine().trim();
int len=str.length();
for(int i=0;i<len;i++)
{
if(str.charAt(i)==Character.toLowerCase(ch) || str.charAt(i)==Character.toUpperCase(ch))
{
list.add(i);
}
}
int pos = 0;
int i = 0;
while(i<str.length())
{
if(str.charAt(i)==Character.toLowerCase(ch) || str.charAt(i)==Character.toUpperCase(ch))
{
String start = str.substring(0,i)+Integer.toString(list.get(pos));
String end = i<=str.length() ? str.substring(i+1) : "";
i = i + Integer.toString(list.get(pos)).length()-1;
pos++;
str = start.concat(end);
}
i++;
}
System.out.print(str);
}
}
I can't see any special bugs. Could be that I lost sight of something. This is my first answer here and English is not my mother tongue, so please excuse any formal errors.
I liked the problem so I made my own answer. apologies for the dirty looking code. :)
Scanner input=new Scanner(System.in);
String firstInput=input.nextLine().charAt(0) + "";
//ensure its lower case
firstInput=firstInput.toLowerCase();
String secondInput=input.nextLine();
//ensure char in secondInput is lower cased too.
secondInput=secondInput.replaceAll(firstInput.toUpperCase(),firstInput);
String[] splitted=secondInput.split(firstInput);
String output="";
int current=0;
for(int i=0;i<splitted.length;i++){
String s=splitted[i];
current=current+ s.length();
if(i==splitted.length-1){
output=output+s;
}else{
output=output+s;
output=output+ current;
current++;
}
}
//edited part, as split doesn't split if firstinput is the last character of the string
if(secondInput.endsWith(firstInput)){
output=output+secondInput.length();
}
System.out.println(output);
Related
INPUT : 123ABC458
OUTPUT : 321ABC854
public static void main(String []args){
String str="123ABC564";
int count=0;
int ans=0;
int firstindex=0;
char[] ch = str.toCharArray();
for(int i=0;i<ch.length;i++){
if(Character.isDigit(ch[i])){
if(ans==0){
firstindex=i;
}
count++;
}
else{
int lastindex=count+firstindex-1;
while(firstindex<lastindex){
char temp=ch[firstindex];
ch[firstindex]=ch[lastindex];
ch[lastindex]=temp;
firstindex++;
lastindex--;
}
ans=0;
count=0;
firstindex=0;
}
}
for (char c : ch){
System.out.print(c);
}
}
}
Can anyone tell me what's wrong with this code
The output which I am getting using this code is 12BA3C564
You can use the Java regex API and StringBuilder to solve it easily. The regex, \d+ specifies one or more digits. Using the Java regex API, you find the numbers, their start position and the end positions which you can use to build the required string.
Demo:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
// Tests
String[] samples = { "123ABC458", "123ABC458XYZ", "123ABC458XYZ367", "ABC123XYZ", "ABC123XYZ" };
for (String s : samples)
System.out.println(numbersInverted(s));
}
static String numbersInverted(String str) {
StringBuilder sb = new StringBuilder();
Matcher matcher = Pattern.compile("\\d+").matcher(str);
int lastInitialPos = 0;
while (matcher.find()) {
int start = matcher.start();
String inverted = new StringBuilder(matcher.group()).reverse().toString();
sb.append(str.substring(lastInitialPos, start)).append(inverted);
lastInitialPos = matcher.end();
}
if (sb.length() == 0) // If no number was found
return str;
else
return sb.append(str.substring(lastInitialPos)).toString();
}
}
Output:
321ABC854
321ABC854XYZ
321ABC854XYZ763
ABC321XYZ
ABC321XYZ
ONLINE DEMO
Here is a concise version using string splitting:
String input = "123ABC458";
String[] parts = input.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
StringBuilder sb = new StringBuilder();
for (String part : parts) {
if (part.matches("\\d+")) {
StringBuilder num = new StringBuilder(part);
sb.append(num.reverse());
}
else {
sb.append(part);
}
}
System.out.println(sb.toString()); // 321ABC854
The splitting operation used above generates a string array of either numbers or letters. Then, we iterate that array and selectively reverse the number strings using StringBuilder#reverse.
This task can be implemented without regular expressions, splitting the input string into substring etc. merely with the help of StringBuilder::insert(int offset, char c) and StringBuilder::append(char c) using simple index calculation for insert:
public static String revertDigits(String str) {
if (str == null || str.isEmpty()) {
return str;
}
StringBuilder sb = new StringBuilder(str.length());
for (int i = 0, j = 0, n = str.length(); i < n; i++) {
char c = str.charAt(i);
if (Character.isDigit(c)) {
sb.insert(j, c); // append in "reverse" mode
} else {
sb.append(c);
j = i + 1; // store the last position of a non-digit
}
}
return sb.toString();
}
Test:
String str="123ABC564";
System.out.println(str + '\n' + revertDigits(str));
Output
123ABC564
321ABC465
Can anyone tell me what's wrong with this code
I believe I have spotted two bugs in your code:
You are never setting ans to anything else than 0. So your if condition ans==0 will always be true. If I have understood the purpose of that variable correctly, you may want to replace it with a boolean called something like insideNumber and set it to true when you detect a digit and to false when you detect that a char is not a digit. Your if statement then becomes if (insideNumber) …
You don’t take a number at the end of your string into account. You can check this statement by appending a letter to your string and see that 564 will then be reversed into 465. To reverse a trailing number correctly: after your loop again check whether you were inside a number, and if so, reverse the last number from firstindex up to the end of the string.
You can get all the numbers from the string as the first move, and then replace the input with the reversed string of the numbers. Example:
public static void main(String[] args)
{
String input = "123ABC458";
Matcher m = Pattern.compile("\\d+").matcher(input);
while(m.find())
input = input.replace(m.group(), new StringBuilder(m.group()).reverse());
System.out.println(input);
}
As an alternative solution, from Java 9 you could also make use of Matcher#replaceAll and reverse every match for 1 or more digits.
String result = Pattern.compile("\\d+")
.matcher("123ABC458")
.replaceAll(m -> new StringBuilder(m.group()).reverse().toString());
System.out.println(result);
Output
321ABC854
Java demo
Hello to all coders out there, any help is appreciated for this is a personal project and not for a school that I thought would be fun, but not turning out to be so. Now the project is to read in an input file, the compare it to a srting[] alphabets = {"a","b","c"...."z"} then to replace the alphabets with another string[] newAlphabets = {"Apple", "Ball", "Cat", .... "Zebra"}. Now I have tried the simple replaceAll() example and it kinda worked. But the plan is to input a .txt file and have the substitution run and output with a new file.
JamesBond.txt: Name is Bond, James Bond.
Output.txt should be: NoAppleMonkeyElephant InsectSnake BallOpenNoDuck, JungelAppleMonkeyElephantSnake BallOpenNoDuck.
Here's what I have so far:
import java.io.IOException;
import java.io.File;
import java.util.Scanner;
public class FnR {
// array of alphabets
static String[] alphabet = {"a","b","c","d","e","f","g","h","i",
"j","k","l","m","n","o","p","q","r","s","t","u",
"v","w","x","y","z"};
// replace the alphabets with substituted string
static String[] newAlphabets =
{"Apple","Bat","Cat","Dog","Egale","Fox","Goat","Horse","Insect","Jungle",
"King","Lion","Monkey","Nose","Open","Push","Quit","Run","Stop","Turn",
"Up","Volume","Water","X-mas","Yes","Zip"};
#SuppressWarnings("resource")
public static void main(String[] arg) throws IOException{
try {
//reads in the file
Scanner input = new Scanner("JamesBond.txt");
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
//prints the txt file out
System.out.println(line);
// replaces the letter j with Jungel in the text regardless of
case
String newtxt1 = line.replaceAll("J","Jungle");
//prints new text
System.out.println(newtxt1);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
} }
Output:
Name is Bond, James Bond
Name is Bond, Jungleames Bond
Not going to give you the code. This answer is providing hints for you to write the code yourself.
Don't use replaceAll(). You'd have to do it 26 times, and that is not really a good solution.
Instead, create a StringBuilder for building up the result string. Then loop through the characters of the input string with a normal for loop using String methods length() and charAt().
Now here is the main "trick" that will simplify your code. Java stores text in Unicode, where letters a to z are stored consecutively. That means you can calculate the index into your newAlphabets array. To do that, you'll write code like this:
char ch = ...;
if (ch >= 'a' && ch <= 'z') {
int idx = ch - 'a'; // number between 0 and 25, inclusive
// use idx here
} else if (ch >= 'A' && ch <= 'Z') {
int idx = ch - 'A'; // number between 0 and 25, inclusive
// use idx here
} else {
// not a letter
}
Hope this helps you write the code yourself.
package stringoperation;
import java.util.Scanner;
public class Stringops {
public static void main(String [] args)
{
String string ;
String sub ;
Scanner in = new Scanner(System.in);
System.out.println("enter a string");
string =in.nextLine();
System.out.println("enter a substring to identify");
sub = in.nextLine();
char[] array= string.toCharArray(); // converting string to array of char
char[] subarray = sub.toCharArray(); //converting sub string to array of char
int count=0;
for(int j=0;j<array.length;j++)
{
if(array[j]==subarray[count]) //till both are same it will run
{
if(count==sub.length()-1) //if substring size is reached thats mean matched break out
{
System.out.println("substring is present");
break;
}
j++;
}
if(array[j]!=subarray[count]) // otherwise make count as 0 to proceed again
{
count=0;
}
}
}
}
The if statement I checked still can't find the error. I am missing something. Just tell me what I am doing wrong.
Try using string.indexOf(sub) != -1, after you're certain that the input strings are in the format you expect; i.e. control characters such as newlines aren't appended to your input data. It's necessary to keep in mind that comparisons will be failed if the Strings you're comparing don't match exactly, i.e.
"example" != "Example".
I've been looking and I can't find anywhere how to write a word count using 3 methods. Here is what the code looks like so far. I'm lost on how to use the methods. I can do this without using different methods and just using one. Please help!!!
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Enter a string: ");
String s = in.nextLine();
if (s.length() > 0)
{
getInputString(s);
}
else
{
System.out.println("ERROR - string must not be empty.");
System.out.print("Enter a string: ");
s = in.nextLine();
}
// Fill in the body with your code
}
// Given a Scanner, prompt the user for a String. If the user enters an empty
// String, report an error message and ask for a non-empty String. Return the
// String to the calling program.
private static String getInputString(String s) {
int count = getWordCount();
while (int i = 0; i < s.length(); i++)
{
if (s.charAt(i) == " ")
{
count ++;
}
}
getWordCount(count);
// Fill in the body
// NOTE: Do not declare a Scanner in the body of this method.
}
// Given a String return the number of words in the String. A word is a sequence of
// characters with no spaces. Write this method so that the function call:
// int count = getWordCount("The quick brown fox jumped");
// results in count having a value of 5. You will call this method from the main method.
// For this assignment you may assume that
// words will be separated by exactly one space.
private static int getWordCount(String input) {
// Fill in the body
}
}
EDIT:
I have changed the code to
private static String getInputString(String s) {
String words = getWordCount(s);
return words.length();
}
private static int getWordCount(String s) {
return s.split(" ");
}
But I can't get the string convert to integer.
You have read the name of the method, and look at the comments to decide what should be implemented inside the method, and the values it should return.
The getInputString method signature should be:
private static String getInputString(Scanner s) {
String inputString = "";
// read the input string from system in
// ....
return inputString;
}
The getWordCount method signature should be:
private static int getWordCount(String input) {
int wordCount = 0;
// count the number of words in the input String
// ...
return wordCount;
}
The main method should look something like this:
public static void main(String[] args) {
// instantiate the Scanner variable
// call the getInputString method to ... you guessed it ... get the input string
// call the getWordCount method to get the word count
// Display the word count
}
count=1 //last word must be counted
for(int i=0;i<s.length();i++)
{
ch=s.charAt(i);
if(ch==' ')
{
count++;
}
}
Use trim() and split() on 1-n whitespace chars:
private static int getWordCount(String s) {
return s.trim().split("\\s+").length;
}
The call to trim() is necessary, otherwise you'll get one extra "word" if there is leading spaces in the string.
The parameter "\\s+" is necessary to count multiple spaces as a single word separator. \s is the regex for "whitespace". + is regex for "1 or more".
What you need to do is, count the number of spaces in the string. That is the number of words in the string.
You will see your count will be off by 1, but after some pondering and bug hunting you will figure out why.
Happy learning!
You can do this by :
private static int getWordCount(String input) {
return input.split("\\s+").length;
}
Use String.split() method like :
String[] words = s.split("\\s+");
int wordCount = words.length;
I'm not sure what trouble you're having with methods but I dont think you need more than one, try this: it uses split to split up the words in a string, and you can chose the delimeters
String sentence = "This is a sentence.";
String[] words = sentence.split(" ");
for (String word : words) {
System.out.println(word);
}
then you can do:
numberOfWords = words.length();
if you want to use 3 methods, you can call a method from your main() method that does this for you, for example:
public String getInputString() {
Scanner in = new Scanner (System.in);
System.out.print("Enter a string: ");
String s = in.nextLine();
if (s.length() > 0) {
return s;
} else {
System.out.println("ERROR - string must not be empty.");
System.out.print("Enter a string: ");
return getInputString();
}
}
public int wordCount(String s) {
words = splitString(s)
return words.length();
}
public String[] splitString(String s) {
return s.split(" ");
}
Based on your code i think this is what you're trying to do:
private static int getWordCount(String input) {
int count = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ' ') {
count++;
}
}
return count;
}
Here's what I've done:
I've moved the code you were 'playing' with into the right method (getWordCount).
Corrected the loop you were trying to use (I think you have for and while loops confused)
Fixed your check for the space character (' ' not " ")
There is a bug in this code which you'll need to work out how to fix:
getWordCount("How are you"); will return 2 when it should be 3
getWordCount(""); will return 0
getWordCount("Hello"); will return 0 when it should be 1
Good luck!
Better use simple function of spilt() with arguments as space
int n= str.split(" ").length;
public static int Repeat_Words(String arg1,String arg2)
{
//It find number of words can be formed from a given string
if(arg1.length() < 1 || arg2.length() < 1)
return 0;
int no_words = 99999;
char[] str1 = arg1.toCharArray();
char[] str2 = arg2.toCharArray();
for(int x = 0; x < str1.length; x++)
{
int temp = 0;
for(int y = 0; y < str2.length; y++)
{
if(str1[x] == str2[y])
temp++;
}
if(temp == 0)
return 0;
if(no_words > temp)
no_words = temp;
temp = 0;
}
return no_words;
}
So the code I have is for a homework assignment where the user inputs a sentence (string) and I need to search through the string and return the smallest word. However, there must be a number inputted at the first spot in the string. Ex: "4 WHAT IS THIS". Output should be "IS" and ignore the number. The only way I figured out how to ignore the number is to make the loop skip over the first spot where the number would be. It works by itself but whenever I put it into the rest of my program it stops working. Is there anyway to make this program cleaner?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Lexicographically smallest word
String TheSentence = sc.nextLine();
String[] myWords = TheSentence.split(" ");
int shortestLengths, shortestLocation;
shortestLengths = (myWords[1]).length();
shortestLocation = 1;
for (int i = 1; i < myWords.length; i++) {
if ((myWords[i]).length() < shortestLengths) {
shortestLengths = (myWords[i]).length();
shortestLocation = i;
}
}
System.out.println(myWords[shortestLocation]);
}
Inside your for loop (that should start at i = 0), add code like this:
try {
double value = Double.parseDouble(myWords[i]);
} catch (NumberFormatException e) {
// add the rest of your code here
}
The idea is that you try to transform your word to a number and if you fail, it means it's not a number, so you can use the length logic on the word.
The first thing you should do is to create the function you want to use instead of mixing the relevant code for the exercice with things like reading a line from the input stream.
You can test whether a character is a letter using Character.isLetter(char).
A good exercice is to build a solution using only that function and looking at each character separately (String.charAt(int) method) in a loop.
The solution is to remember where the currently shortest word starts and how long it is.
In practice, I would just use regexes like this:
public static String shortestWord(String sentence) {
String shortest = null;
Pattern word = Pattern.compile("\\w+");
Matcher m = word.matcher(sentence);
while (m.find()) {
String candidate = m.group();
if (shortest == null || shortest.length() > candidate.length())
shortest = candidate;
}
return shortest;
}
You could try using substring, e.g.
String result=inputString.substring(1)
'1' being the second letter in the string, substring returning every value save for the first.
The below basically just shortens up your code..other than that it doesn't change much. That being said..it would be much better to create all this in a method called shortestWord() or something. There is really no reason the code below shouldn't work though.
Revised Code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] myWords = (sc.nextLine()).split(" ");
int shortestLocation = 1
for (int i = 2; i < myWords.length; i++) { // No reason to start at 1 as you have
// already made shortestLocation = 1
if (myWords[i].length() < myWords[shortestLocation].length()) {
shortestLocation = i;
}
}
System.out.println(myWords[shortestLocation]);
}
Suggested Code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] myWords = (sc.nextLine()).split(" ");
System.out.println("The shortest word is: " + shortestWord(myWords));
}
public static String shortestWord(String[] myWords) {
int shortestLocation = 1
for (int i = 2; i < myWords.length; i++) { // No reason to start at 1 as you have
// already made shortestLocation = 1
if (myWords[i].length() < myWords[shortestLocation].length()) {
shortestLocation = i;
}
}
return myWords[shortestLocation];
}