How to read a textfile in java? - java

How to select numbers from a line by line text file that has both text and numbers?
For example:
[10] begin0-1-selp-2-yelp-25-jelp-21-hi-35-ou
I want to only have 0 1 2 25 21 35 printed out without the [10]. But I keep getting 10012252135.
This is my code
try {
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
String i = scan.nextLine();
String final_string = "";
for (int j = 0; j < i.length(); j++) {
char myChar = i.charAt(j);
if (Character.isDigit(myChar)) {
final_string = final_string.concat(Character.toString(myChar));
}
}
System.out.println(final_string);
}
scan.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}

String tt = "[10] begin0-1-selp-2-yelp-25-jelp-21-hi-35-ou";
tt = tt.replaceAll("\\[.*\\]",""); // IT get rid of any [AnyNumber]
tt = tt.replaceAll("\\D+",""); // It get rid of any char that is not a letter
System.out.println(tt);
I made a regex I can't make it one line but the output is the disered.
OutPut
012252135

I like the answer from Reaz Murshed,
but just in case you have multiple occurenses of number enclosed in "[]" you might filter those by remembering if you are currently in just an enclosed scope or not:
char NON_NUMERIC_SCOPE_START = '[';
char NON_NUMERIC_SCOPE_END = ']';
try {
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
String i = scan.nextLine();
String final_string = "";
boolean possibleNumericScope = true;
for (int j = 0; j < i.length(); j++) {
char myChar = i.charAt(j);
if (myChar == NON_NUMERIC_SCOPE_START) {
possibleNumericScope = false;
} else if (myChar == NON_NUMERIC_SCOPE_END && !possibleNumericScope) {
possibleNumericScope = true;
} else if (Character.isDigit(myChar) && possibleNumericScope) {
final_string = final_string.concat(Character.toString(myChar));
}
}
System.out.println(final_string);
}
scan.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}

I think the first portion is the line number which can be easily ommited by splitting your String by space. Please try the following code.
String i = "[10] begin0-1-selp-2-yelp-25-jelp-21-hi-35-ou";
String final_string = "";
// Split the String with space to remove the first portion which
// might be indicating the line number or something like that.
String[] splittedArray = i.split(" ");
// Then just run the loop in the second item of the split
// `String` array.
int contCount = 0;
for (int j = 0; j < splittedArray[1].length(); j++) {
char myChar = splittedArray[1].charAt(j);
if (Character.isDigit(myChar)) {
contCount = 0;
final_string = final_string.concat(Character.toString(myChar));
} else {
if (contCount == 0)
final_string = final_string + " ";
contCount++;
}
}
System.out.println(final_string);

I added a line to get rid of [line-number] before the loop:
i = i.substring(i.indexOf("]")+1);
for (int j = 0; j < i.length(); j++) {
This should do the trick.

If you always have the [10], then you can just edit your final_string to be everything but the first two numbers. Change System.out.println(final_string) to System.out.println(final_string.substring(2)). Then, if you need spaces, type final_string += " "; in your if statement of the for loop.

Try this:
String y = "[133] begin0-1-selp-2-yelp-25-jelp-21-hi-35-ou";
String result = y.replaceAll("\\[[0-9]*\\]|[a-zA-Z-]*", "");
Or
String y = "[133] begin0-1-selp-2-yelp-25-jelp-21-hi-35-ou";
String result = y.replaceAll("\\[[\\d]*\\]|[^\\d]", "");
Many ways to do this :)

Related

How to split a String into an Array if a .contains() condition is met?

I'm doing a hackerrank medium challenge for a password cracker. I want to be able to check if a given string, attempt, contains all the words in pass. pass is an array of passwords and attempt is a concatenation of random entries in pass. If attempt contains ONLY words that are found as entries in pass, then it is deemed a good password and the words from the input of attempt, limited with spaces, is printed.
Sample Input
3 //3 attempts
6 //6 words for attempt 1
because can do must we what //pass[]
wedowhatwemustbecausewecan //attempt
2 //...
hello planet
helloworld
3
ab abcd cd
abcd
Expected Output
we do what we must because we can
WRONG PASSWORD //Because planet is not in pass[]
ab cd
Code
public class Solution {
static String passwordCracker(String[] pass, String attempt) {
int arrayLength=pass.length;
int accuracy=0;
String trips_array[] = new String[pass.length];
String [] newWord = new String[20];
for (int i=0; i<pass.length;i++)
{
// int j=0;
String[] arr = pass[i].split(" ");
//-------------------------------
if (attempt.contains(pass[i]))
{
accuracy++;
newWord[i] = pass[i];
trips_array[i] = attempt.split(" ");
}
//------------------------------
}
StringBuilder sb = new StringBuilder();
for (String words : trips_array) {
sb.append(words);
}
for (int i=0; i<pass.length;i++)
{
if (accuracy==pass.length)
return sb.toString() + " ";
else
return "WRONG PASSWORD";
}
return "test";
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
int n = in.nextInt();
String[] pass = new String[n];
for(int pass_i = 0; pass_i < n; pass_i++){
pass[pass_i] = in.next();
}
String attempt = in.next();
String result = passwordCracker(pass, attempt);
System.out.println(result);
}
in.close();
}
}
The part in focus is the part in the //----------------- comment section. Basically, my goal is to see if the attempt contains the correct entries in pass, and if so, save that substring of the attempt (or similarly, the entry in pass) to a new array which can be printed in the correct order. If you check the expected output above, you'll see that the output is the same as attempt except with spaces.
Essentially, I would need to find the breaks in the words of attempt and print that if it fulfills the above requirements (first paragraph).
See this for more details
https://www.hackerrank.com/challenges/password-cracker/problem
If it helps you
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int testNumb = Integer.parseInt(reader.readLine());
List<String> passList = new ArrayList<>();
List<String> attList = new ArrayList<>();
for (int i = 0; i < testNumb; i++) {
reader.readLine();
passList.add(reader.readLine());
attList.add(reader.readLine());
}
reader.close();
for (int i = 0; i < testNumb; i++) {
String s1 = passList.get(i);
String s2 = attList.get(i);
StringBuilder sb = new StringBuilder();
String[] s1Arr = s1.split(" ");
while (s2.length() > 0) {
int s2Lenght = s2.length();
for (String s : s1Arr) {
if (s2.startsWith(s)) {
sb.append(s + " ");
s2 = s2.substring(s.length());
}
}
if (s2.length() == s2Lenght) {
sb = new StringBuilder("wrong pass");
break;
}
}
System.out.println(sb.toString());
}
Your for loop looks too complicated, here is how I would approach that part.
boolean isAllWords = true;
int checksum = 0;
for (int j = 0; j < pass.length; j++) {
if (!attempt.contains(pass[j]) {
isAllWords = true;
break;
}
checksum += pass[j].length;
}
if (isAllWords && checksum == attempt.length) {
//This means attempt contains all words in pass array and nothing more
//... handle successful attempt
} else {
//... handle bad attempt
}

How to remove String from another String?

I want to remove a string from another string, not all the letters.
example: "hello world my name is john"
removing: "ewo"
result: "hllo rld my name is john"
my program deletes all the letters that are from removing
String text = "hello world my name is john";
int num = 1;
for (int i = 0; i < num; i++) {
String del = ewo;
String[] delArray = del.split("");
for (int j = 0; j < delArray.length; j++) {
text = text.replace(delArray[j], "");
}
System.out.println(text);
}
My program return: "hll rld my nam is jhn", but that's not what I need
Try this
String text = "hello world my name is john";
int num = 1;
for (int i = 0; i < num; i++) {
String del = ewo;
String[] delArray = del.split("");
for (int j = 0; j < delArray.length; j++) {
text = text.replaceFirst(delArray[j], "");
}
System.out.println(text); //output => hll orld my name is john
}
From your preferred output, I take it you want to replace only the first matching character. Luckily, Java has a method for this.
Replace this line:
text = text.replace(delArray[j], "");
With this one:
text = text.replaceFirst(delArray[j], "");
And it now only removes the first matching character, as desired.
You can use replaceFirst() instead of replace().It will remove the first occurrency matching with your input.
System.out.prinln("hello world my name is john".replace("orld",""));
You can use replaceFirst() or you can use three loops each for removing e, w, and o and use a break statement thereafter.
This might be what you want
public static void main(String[] args) {
String str1 = "hello world my name is john";
String str2 = "ewo";
int currentCharIndex = 0;
StringBuilder resultBuilder = new StringBuilder();
for (char c : str1.toCharArray()) {
if (currentCharIndex >= str2.length() || c != str2.charAt(currentCharIndex)) {
resultBuilder.append(c);
} else {
currentCharIndex++;
}
}
System.out.println(resultBuilder.toString());
}

parsing/converting task with characters and numbers within

It is necessary to repeat the character, as many times as the number behind it.
They are positive integer numbers.
case #1
input: "abc3leson11"
output: "abccclesonnnnnnnnnnn"
I already finish it in the following way:
String a = "abbc2kd3ijkl40ggg2H5uu";
String s = a + "*";
String numS = "";
int cnt = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
numS = numS + ch;
cnt++;
} else {
cnt++;
try {
for (int j = 0; j < Integer.parseInt(numS); j++) {
System.out.print(s.charAt(i - cnt));
}
if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {
System.out.print(s.charAt(i));
}
} catch (Exception e) {
if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {
System.out.print(s.charAt(i));
}
}
cnt = 0;
numS = "";
}
}
But I wonder is there some better solution with less and cleaner code?
Could you take a look below? I'm using a library from StringUtils from Apache Common Utils to repeat character:
public class MicsTest {
public static void main(String[] args) {
String input = "abc3leson11";
String output = input;
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(input);
while (m.find()) {
int number = Integer.valueOf(m.group());
char repeatedChar = input.charAt(m.start()-1);
output = output.replaceFirst(m.group(), StringUtils.repeat(repeatedChar, number));
}
System.out.println(output);
}
}
In case you don't want to use StringUtils. You can use the below custom method to achieve the same effect:
public static String repeat(char c, int times) {
char[] chars = new char[times];
Arrays.fill(chars, c);
return new String(chars);
}
Using java basic string regx should make it more terse as follows:
public class He1 {
private static final Pattern pattern = Pattern.compile("[a-zA-Z]+(\\d+).*");
// match the number between or the last using regx;
public static void main(String... args) {
String s = "abc3leson11";
System.out.println(parse(s));
s = "abbc2kd3ijkl40ggg2H5uu";
System.out.println(parse(s));
}
private static String parse(String s) {
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
int num = Integer.valueOf(matcher.group(1));
char prev = s.charAt(s.indexOf(String.valueOf(num)) - 1);
// locate the char before the number;
String repeated = new String(new char[num-1]).replace('\0', prev);
// since the prev is not deleted, we have to decrement the repeating number by 1;
s = s.replaceFirst(String.valueOf(num), repeated);
matcher = pattern.matcher(s);
}
return s;
}
}
And the output should be:
abccclesonnnnnnnnnnn
abbcckdddijkllllllllllllllllllllllllllllllllllllllllggggHHHHHuu
String g(String a){
String result = "";
String[] array = a.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
//System.out.println(java.util.Arrays.toString(array));
for(int i=0; i<array.length; i++){
String part = array[i];
result += part;
if(++i == array.length){
break;
}
char charToRepeat = part.charAt(part.length() - 1);
result += repeat(charToRepeat+"", new Integer(array[i]) - 1);
}
return result;
}
// In Java 11 this could be removed and replaced with the builtin `str.repeat(amount)`
String repeat(String str, int amount){
return new String(new char[amount]).replace("\0", str);
}
Try it online.
Explanation:
The split will split the letters and numbers:
abbc2kd3ijkl40ggg2H5uu would become ["abbc", "2", "kd", "3", "ijkl", "40", "ggg", "2", "H", "5", "uu"]
We then loop over the parts and add any strings as is to the result.
We then increase i by 1 first and if we're done (after the "uu") in the array above, it will break the loop.
If not the increase of i will put us at a number. So it will repeat the last character of the part x amount of times, where x is the number we found minus 1.
Here is another solution:
String str = "abbc2kd3ijkl40ggg2H5uu";
String[] part = str.split("(?<=\\d)(?=\\D)|(?=\\d)(?<=\\D)");
String res = "";
for(int i=0; i < part.length; i++){
if(i%2 == 0){
res = res + part[i];
}else {
res = res + StringUtils.repeat(part[i-1].charAt(part[i-1].length()-1),Integer.parseInt(part[i])-1);
}
}
System.out.println(res);
Yet another solution :
public static String getCustomizedString(String input) {
ArrayList<String > letters = new ArrayList<>(Arrays.asList(input.split("(\\d)")));
letters.removeAll(Arrays.asList(""));
ArrayList<String > digits = new ArrayList<>(Arrays.asList(input.split("(\\D)")));
digits.removeAll(Arrays.asList(""));
for(int i=0; i< digits.size(); i++) {
int iteration = Integer.valueOf(digits.get(i));
String letter = letters.get(i);
char c = letter.charAt(letter.length()-1);
for (int j = 0; j<iteration -1 ; j++) {
letters.set(i,letters.get(i).concat(String.valueOf(c)));
}
}
String finalResult = "";
for (String str : letters) {
finalResult += str;
}
return finalResult;
}
The usage:
public static void main(String[] args) {
String testString1 = "abbc2kd3ijkl40ggg2H5uu";
String testString2 = "abc3leson11";
System.out.println(getCustomizedString(testString1));
System.out.println(getCustomizedString(testString2));
}
And the result:
abbcckdddijkllllllllllllllllllllllllllllllllllllllllggggHHHHHuu
abccclesonnnnnnnnnnn

Boolean 2d array text file

I need to read a series of # and blank spaces from a text file and print it as a maze.
public static void readMaze() throws FileNotFoundException{
String fileName = "path/maze.txt";
Scanner input = new Scanner(new File(fileName));
int x = 0;
String columns = "";
while (input.hasNextLine()){
x++;
columns = input.nextLine();
}
int col = columns.length();
boolean maze[][] = new boolean[x][col];
}
So I have got the number of rows(x) and the number of columns which the maze will have.
Next step is to create a boolean array with a true value for each "#" and false for each blank space in the file and I am not sure how to do this.
while (input.hasNextLine()){
columns = input.nextLine();
for (int c = 0; c < columns.length();c++){
if (c == '#'){
add true;
}
else{
add false;
}
}
}
So that is the next part, but I am not sure wht I need to put in the for loop, guidance would be appreciated.
The only missing part of your puzzle is this
int row = 0;
while (input.hasNextLine()){
columns = input.nextLine();
for (int c = 0; c < columns.length();c++){
c = columns.charAt(c);
if (c == '#'){
result[row, c] = true;
}
else{
result[row, c] = false; // not even needed, false is the default value ;)
}
row ++;
}
Should be better with something like :
ArrayList<Boolean> returnArray = new ArrayList<Boolean>()
for (int c = 0; c < columns.length();c++){
if (columns[c].equals("#")){
returnArray.add(true);
}
else{
returnArray.add(false);
}
}
return returnArray.hasArray();
int i = 0;
while(input.hasNextLine())
{
row = input.nextLine();
String[] row_temp = row.split("(?!^)");
int row_length = row_temp.length();
for(int j=0; j<row_length; j++){
if(row_temp[j].matches("#")){
maze[i][j] = true;
}
else{
maze[i][j] = false;
}
}
i++;
}

how to convert "user_id" to "userId" in Java? [duplicate]

This question already has answers here:
What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?
(22 answers)
Closed 7 years ago.
convert string to camelCase
eg:
"user_id" to "userId"
"user_name" to "userName"
"country_province_city" to "countryProvinceCity"
how to do that in a easy way?
ps:"country_province_city" should be "countryProvinceCity" not "countryprovincecity"
I would use a loop and a StringBuilder. Something like
String[] arr = { "user_id", "user_name", "country_province_city" };
for (String str : arr) {
StringBuilder sb = new StringBuilder(str);
int pos;
while ((pos = sb.indexOf("_")) > -1) {
String ch = sb.substring(pos + 1, pos + 2);
sb.replace(pos, pos + 2, ch.toUpperCase());
}
System.out.printf("%s = %s%n", str, sb);
}
And I get the (requested)
user_id = userId
user_name = userName
country_province_city = countryProvinceCity
As Fast Snail mentions, simply use, for example, if String str = "user_id, user_name, user_id";, call str = str.replaceAll("userID", "user_id");, causing str to now have the value "userID, user_name, userID"
Alternatively, a more complete method would be as follows
public String toCamel(String str) {
String[] splits = str.split("_");
for (int i = 1; i < splits.length; i++) {
char first = Character.toUpperCase(splits.charAt(0));
if (splits[i].length() > 0)
splits[i] = first + splits[i].substring(1);
else
splits[i] = first + "";
}
String toRet = "";
for (String s : splits)
toRet += s;
return toRet;
}
This is a very simple one:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String result = "";
String input = scan.nextLine();
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '_') {
result += input.toUpperCase().charAt(i + 1);
i = i + 1;
} else {
result += input.toLowerCase().charAt(i);
}
}
System.out.println(result);
}
if you like to do it many times, I advice you to use a while loop to keep repeating the same code over and over again:
while (true) {
//the previous code
}
http://commons.apache.org/proper/commons-lang/javadocs/api-3.4/index.html
String str="country_province_city";
wordUtils.capitalize(str, '_');
str=str.replaceAll("_", "");
output: countryProvinceCity
For another point of view that the answers above you can also do it with split function and two loops, like this:
String[] strings = {"user_id","user_name","country_province_city"};
for (int i = 0; i < strings.length; i++)
{
String string = strings[i];
String totalString = "";
String[] divide = string.split("_");
for(int j = 0; j < divide.length; j++)
{
if(j != 0)
{
divide[j] = "" + divide[j].toUpperCase().charAt(0) + divide[j].substring(1,divide[j].length());
}
totalString = totalString + divide[j];
}
}
If you want to show this changed Strings by console you just have to add System.out.println after the second loop and inside the first one, like this:
for (int i = 0; i < strings.length; i++)
{
//The same code as the code that I put in the example above
for(int j = 0; j < divide.length; j++)
{
//The same code as the example above
}
System.out.println(totalString);
}
On the contrary, if your objective it's to store them into an array, you can do it like this:
String[] store;
for (int i = 0; i < strings.length; i++)
{
//The same code as the code that I put in the example above
store = new String[divide.length];
for(int j = 0; j < divide.length; j++)
{
//The same code as the example above
}
store[j] = totalString;
}
If you have any doubt about the code please let me know.
I expect it will help to you!

Categories

Resources