I have large text files and they each contain strings of words and numbers.
I need to increase those numbers by a fixed value and write them right back to where they were before within that string.
The value that I want to add depends on the word that came before the number, and every number that has none of these keywords must not be increased.
My approach would be to split at space characters, check for the words and handle the digit after, whenever I find the keyword. However, this leaves me with the requirement of having space characters between word and number and that is not ensured.
Furthermore, when reassembling the string from the split array, this might break the layout from before.
An example could be
"Mark is quite large, 189cm, and was born in the year 1978. However, he has only 1 question concerning parsing, that he really can't get his head around."
After large, the height should be increased by 5 and after year, the number subtracted by 19. The number 1 should stay untouched, as only is not a keyword.
I can work with both, java or python, as these are the languages I know.
I think i got something:
public class Start {
public static void main(String[] args){
//Test String
String s = "not4inc6desc3inc14";
StringBuffer sb = new StringBuffer(s);
//keep track where new word begins
int newWord = 0;
for(int i = 0; i < sb.length(); i++){
//chekc if the new Character is a number
if(checkNumber(sb.substring(i, i+1))){
//if the old word ends with "inc"
//maybe try out .contains()
if(sb.substring(newWord, i).endsWith("inc")){
//replace number
StringBuffer temp = new StringBuffer();
int j = 0;
//get full number
for(j = i; j < sb.length() && checkNumber(sb.substring(j, j+1)); j++){
temp.append(sb.substring(j, j+1));
}
//modify number
int number = Integer.parseInt(temp.toString()) + 1;
//replace number
sb.replace(i, i + temp.length(), Integer.toString(number));
//number no longer needs to be checked for being a word
i=j;
}
}
}
//print test String
System.out.println(sb.toString());
}
// Check if String is numeric
private static boolean checkNumber(String s){
try{
Integer.parseInt(s);
}catch(NumberFormatException e ){
return false;
}
return true;
}
}
I'm sorry it's a bit hard to understand... feel free to ask...
Related
Say I have the string: "Polish". which is indexed as: P=0,O=1, L=2, I=3, S=4, H=5
I want to be able to type something like
" word1.arrangebyindex(051423) "
and have word2 equal PHOSLI
I want to be able to type in any combination of index values and have it rearranged to a new word.
I'm trying to write a program that will rearrange a given word in the following way:
The first character of the word is followed by the last character of the word which is followed by the second character and then the second last character of the word and so on. If the given word has an odd number of characters, then the middle character is repeated again. For example, given the word "mouse" it should be encoded as "meosuu"
I suggest making a hashmap, which allows the user to enter in a letter, which would be the key and a number, which would be the value.
Once you associate all the letters with the number as a key and a value (such as P: 0 and H:5), then you can use your hashmap to create a string based on the numbers given to you.
Break each number down by digits (note that it will be more difficult to implement if a word is associated with a multiple digit number) and add to the string depending on what number you have called.
Here's the hashmap api: https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
Just look at the method summary and try those. I doubt you'll need much else out of the rest of the api.
If you use HashMap then key as integer and value should be character because if string = APPLE then 0-A 1-P 2-P 3-L 4-E.
or you should go through this way:
public class ModifiedIndex {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
char [] ch = str.toCharArray();
String s ="";
int i=0;
int j = str.length()-1;
if(str.length()%2 == 0)
{
for(int k = 0; k < str.length()/2; k++)
{
s = s+ch[i] +ch[j];
i++;
j--;
}
}
else
{
for(int k = 0; k < str.length(); k++)
{ if(i<=j)
{
s = s+ch[i] +ch[j];
i++;
j--;
}
}
}
}
}
This is the instructions i got from my teacher:
Write your code in the file WordCount.java. Your code should go into a method with the following signature. You may write your own main method to test your code. The graders will ignore your main method:
public static int countWords(String original, int minLength){}
Your method should count the number of words in the sentence that meet or exceed minLength (in letters). For example, if the minimum length given is 4, your program should only count words that are at least 4 letters long.
Words will be separated by one or more spaces. Non-letter characters (spaces, punctuation, digits, etc.) may be present, but should not count towards the length of words.
Hint: write a method that counts the number of letters (and ignores punctuation) in a string that holds a single word without spaces. In your countWords method, break the input string up into words and send each one to your method.
This is my code:
public class WordCount {
public static void main(String[] args)
{
System.out.print("Enter string: ");
String input = IO.readString();
System.out.print("Enter minimum length for letter: ");
int length = IO.readInt();
IO.outputIntAnswer(countWords(input, length));
}
public static int countWords(String original, int minLegth)
{
int count = 0;
int letterCount = 0;
for(int i = 0; i < original.length(); i++)
{
char temp = original.charAt(i);
if(temp >= 'A' && temp <= 'Z' || temp >= 'a' && temp <= 'z')
{
letterCount++;
}
else if(temp == ' '|| i == original.length()-1)
{
if(letterCount >= minLegth)
{
count++;
}
letterCount = 0;
}
}
return count;
}
}
My college uses an autograder to grade project and i am keep getting one of the test case wrong. Can someone help me figure out what the problem is?
I figured the problem that your code is not able to compare the last character.It expects a space after the last character so that it can compare the last character since java doesn't use null character terminator for string termination.I have emulated the same code using Scanner class as I was having some trouble with io.So I have done the following change:
Scanner sc1,sc2;
sc1=new Scanner(System.in);
String input = sc1.nextLine()+" ";
I don't know if its possible to do:
String input = IO.readString()+" ";
but i think you should try appending blank space " " at the end of the string
First off i am pretty fresh when it comes to java. My program is supposed to ask the user for strings and print what they just put in. It is then supposed to change all characters to lowercase and remove all spaces from the strings and print this. After this, it is supposed to print a character array of the alphabet and use an asterisk (*) to show each time a character occurs in the string (I dont even know where to start here). Right now it just prints the String in an array(not correct). This is what I have so far. It will print either the string with no spaces or the original but not both. My object/array naming is atrocious and i apologize in advance. Any guidance would be greatly appreciated
EDIT: here is the question
In this assignment you are to write a program that will do the following:
Ask the user to input a positive integer m, and then read that integer. Use a
Scanner object declared in main to read this integer.
Call a method that will ask the user to input m strings. As the strings are
read, they should be concatenated into a single string st. After reading the m strings and forming the single string st, the method should return st. NOTE: This method will have two parameters, an int to receive m and a Scanner object to receive the Scanner object declared in main.
In main print the concatenated string received from the method.
In main convert the String object to lower case.
In main convert the lower case String object to an array of char. (All letters
will be lower case.)
In main print the character array just created. (Requires a looping structure.)
Call a method that will compress the character array in the following way.
The method will count the letters of the alphabet in the array, create a new array whose size is equal to that count, and copy only the letters of the original array into the new array. Return the new array.
In main declare an integer array of size 26. Call a method with two parameters, a character array x (which will contain only lower case letters, and an integer array z that will receive the one declared in main). The method will set all entries in the integer array to zero. It will then process through the lower case letter array and count the number of times each letter occurs. HINT: z[x[i]-97]++ can do the counting. The ASCII code for a is 97, so if x[i] is ‘a’, then z[0] will be incremented. ‘b’ would cause z[1] to be incremented, etc. The integer array now contains a frequency distribution for the letters in the array of lowercase letters.
Call a method with one integer array parameter (which will receive the frequency distribution array) and print each letter on a new line followed by the number of stars equal to the integer value in that array element. This must be neatly aligned. Hint: if i is an index with 0 ≤ 𝑖 ≤ 25, then (char)(i+97) is a lower case letter of the alphabet.
package lab6;
import java.util.Scanner;
public class Lab6 {
public char sent[];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter the number of strings you want: ");
int m = input.nextInt();
Lab6 loo = new Lab6();
loo.print(loo.loop(m));
}
public String loop(int m) { //print the string that was entered
String total = " ";
for (int i = 1; i <= m; i++) {
Scanner input = new Scanner(System.in);
System.out.println("enter string: " + i);
String st = input.nextLine();
total += st + "";
}
System.out.println(total);
return total;
}
public void print(String ht) { //print array
String st = ht.toLowerCase().replaceAll("\\s", "");
sent = st.toCharArray();
for (int i = 0; i < sent.length; i++) {
System.out.println(sent[i]);
}
}
}
Sounds like computer science is not your cup of tea. I Strongly recommend you refactor this code and try to figure out why it does what it does.
public void print(String ht) { // print array
String st = ht.toLowerCase().replaceAll("\\s", "");
sent = st.toCharArray();
int[] alphabet = new int[26];
//set all values to 0
for(int i = 0 ; i < alphabet.length ; i++){
alphabet[i] = 0;
}
//Loop through all characters and increment corresponding value
for(int i = 0 ; i < sent.length ; i++){
alphabet[sent[i] - 97]++;
}
//Print character + asterisk for each time the character is used
for(int i = 0 ; i < alphabet.length ; i++){
System.out.print((char)(i + 97) + ": ");
for(int nChars = 0 ; nChars < alphabet[i] ; nChars++){
System.out.print("*");
}
System.out.println();
}
}
This question already has answers here:
Reverse a given sentence in Java
(14 answers)
Closed 9 years ago.
I m inserting a string in my program
String str = " I live in India";
how can in get reversed string of that like
String str ="India in live I"
this is an interview question in my interview. Please any one can help me out in this question
Split it and then add it to a new String in reverse order.
String s = " I live in India";
String[] split = s.split(" ");
String result = "";
for (int i = split.length - 1; i >= 0; i--) {
result += (split[i] + " ");
}
System.out.println(result.trim());
This prints:
India in live I
Although short and straight-forward, this solution is not really effective in terms of time and memory. It somewhat depends on how the input is given (as a String or as something else) and whether we can modify the input in order to save computation resources.
Let's assume the sentence is given as an array of characters and we are allowed to modify it. We can then follow the following approach, which brings linear time (O(n)) and constant (O(1)) memory complexity:
What we will have as input would be:
char[] array = {'I',' ','l','i','v','e',' ','i','n',' ','I','n','d','i','a'};
Let's write a method that takes a char[] array and reverses the elements from start to end in-place:
void reverse(char[] array, int start, int end) {
while (start < end) {
char temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
First, we will reverse the whole array (in-place), using this method.
You can notice that after the reversal the words in the sentence are ordered in the desired (reversed) way. The problem is that each word is reversed:
{'a','i','d','n','I',' ','n','i',' ','e','v','i','l',' ','I'}
Let's now iterate the array from left to the right. We will reverse each word in-place, like we initially reversed the whole array. In order to do that, we need to keep an index (start), telling where does a word start and every time we encounter a space (' ') we will trigger a reverse between start and the character before the space. This way we will keep the desired order of words, but we will also have the characters in the words properly ordered.
The code should be self-explanatory:
void reverseSentence(char[] array) {
int n = array.length;
reverse(array, 0, n - 1);
int start = 0;
for (int i = 0; i < n; i++) {
if (array[i] == ' ') {
reverse(array, start, i - 1);
start = i + 1;
}
}
}
Calling this on the initial array, we get:
{'I','n','d','i','a',' ','i','n',' ','l','i','v','e', ' ','I'}
We can further construct a String out of it, or just print it. In any case, the sentence is reversed as desired.
This has linear complexity (O(n)), because each character is part of a reverse exactly once and is being tested for being a space exactly once.
As for memory-usage, we used only one additional variable (start), which makes the total memory complexity a constant (O(1)).
String str = "I live in India";
String result = "";
String[] words = str.split(" ");
for (int i=words.length-1;i>=0;i--){
result = result + words[i] + " ";
}
result = result.subString(result, 0, result.length-1); // remove the last " "
This code splits the String along the whitespaces, so that you get an array of the words.
Then a for loop iterates through the array from last to first element and appends the words plus a whitespace to the result string. Finally the whitepace after the last word is removed.
try this way
public class test {
public static void main(String args[])
{
String x="i live in india";
String y[]=x.split(" ");
System.out.println(y[3]+" "+y[2]+" "+y[1]+" "+y[0]);
// if the input string is different meaning if the number of words are greater than or less than four then try this way
/*for(int i=y.length-1;i>=0;i--)
{
System.out.print(y[i]+ " ");
}*/
}
}
this is the screenshot to show the output
This question already has answers here:
Java compressing Strings
(21 answers)
Closed 8 years ago.
I am trying to write a Java program which takes in as input a string and counts the number of occurrences of characters in a string and then prints a new string having the character followed by the no of occurrences.
E.G.
Input String:
aaaabb
Output String:
a4b2
Input String:
aaaaabbbc
Output String:
a5b3c1
I am posting my java code.
It is throwing StringOutOfBoundException
/*Write a routine that takes as input a string such as "aabbccdef" and o/p "a2b2c2def" or "a4bd2g4" for "aaaabddgggg".*/
import java.util.Scanner;
public class CountingOccurences {
public static void main(String[] args) {
Scanner inp= new Scanner(System.in);
String str;
char ch;
int count=0;
System.out.println("Enter the string:");
str=inp.nextLine();
while(str.length()>0)
{
ch=str.charAt(0);
int i=0;
while(str.charAt(i)==ch)
{
count =count+i;
i++;
}
str.substring(count);
System.out.println(ch);
System.out.println(count);
}
}
}
This is the problem:
while(str.charAt(i)==ch)
That will keep going until it falls off the end... when i is the same as the length of the string, it will be asking for a character beyond the end of the string. You probably want:
while (i < str.length() && str.charAt(i) == ch)
You also need to set count to 0 at the start of each iteration of the bigger loop - the count resets, after all - and change
count = count + i;
to either:
count++;
... or get rid of count or i. They're always going to have the same value, after all. Personally I'd just use one variable, declared and initialized inside the loop. That's a general style point, in fact - it's cleaner to declare local variables when they're needed, rather than declaring them all at the top of the method.
However, then your program will loop forever, as this doesn't do anything useful:
str.substring(count);
Strings are immutable in Java - substring returns a new string. I think you want:
str = str.substring(count);
Note that this will still output "a2b2a2" for "aabbaa". Is that okay?
public class StringTest{
public static void main(String[] args){
String s ="aaabbbbccccccdd";
String result="";
StringBuilder sb = new StringBuilder(s);
while(sb.length() != 0){
int count = 0;
char test = sb.charAt(0);
while(sb.indexOf(test+"") != -1){
sb.deleteCharAt(sb.indexOf(test+""));
count++;
}
//System.out.println(test+" is repeated "+count+" number of times");
result=result+test+count;
}
System.out.println(result);
}
}
I don't want to give out the full code. So I want to give you the challenge and have fun with it. I encourage you to make the code simpler and with only 1 loop.
Basically, my idea is to pair up the characters comparison, side by side. For example, compare char 1 with char 2, char 2 with char 3, and so on. When char N not the same with char (N+1) then reset the character count. You can do this in one loop only! While processing this, form a new string. Don't use the same string as your input. That's confusing.
Remember, making things simple counts. Life for developers is hard enough looking at complex code.
Have fun!
Tommy "I should be a Teacher" Kwee
if this is a real program and not a study project, then look at using the Apache Commons StringUtils class - particularly the countMatches method.
If it is a study project then keep at it and learn from your exploring :)
You should be able to utilize the StringUtils class and the countMatches() method.
public static int countMatches(String str,
String sub)
Counts how many times the substring appears in the larger String.
Try the following:
int count = StringUtils.countMatches("a.b.c.d", ".");
I think what you are looking for is this:
public class Ques2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine().toLowerCase();
StringBuilder result = new StringBuilder();
char currentCharacter;
int count;
for (int i = 0; i < input.length(); i++) {
currentCharacter = input.charAt(i);
count = 1;
while (i < input.length() - 1 && input.charAt(i + 1) == currentCharacter) {
count++;
i++;
}
result.append(currentCharacter);
result.append(count);
}
System.out.println("" + result);
}
}
Try this:
import java.util.Scanner;
/* Logic: Consider first character in the string and start counting occurrence of
this character in the entire string. Now add this character to a empty
string "temp" to keep track of the already counted characters.
Next start counting from next character and start counting the character
only if it is not present in the "temp" string( which means only if it is
not counted already)
public class Counting_Occurences {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter String");
String str=input.nextLine();
int count=0;
String temp=""; // An empty string to keep track of counted
// characters
for(int i=0;i<str.length();i++)
{
char c=str.charAt(i); // take one character (c) in string
for(int j=i;j<str.length();j++)
{
char k=str.charAt(j);
// take one character (c) and compare with each character (k) in the string
// also check that character (c) is not already counted.
// if condition passes then increment the count.
if(c==k && temp.indexOf(c)==-1)
{
count=count+1;
}
}
if(temp.indexOf(c)==-1) // if it is not already counted
{
temp=temp+c; // append the character to the temp indicating
// that you have already counted it.
System.out.println("Character " + c + " occurs " + count + " times");
}
// reset the counter for next iteration
count=0;
}
}
}