How can I take out some parts of the String? - java

I have a String value like this.
"Apple:1#Banana:2#Cake:3#Dog:4#Elephant:5"
a word : a number # a word : a number ...
and I want to separate the Strings into:
Apple
1
Banana
2
Cake
3
Dog
4
Elephant
5
...
However, I do not know how long the String is. Is there any way I can split each content connected with ":" and "#"?

Split on : or #:
String[] parts = str.split("[:#]");

You can replace all : symbol to # and split the string by #.
String str = "Apple:1#Banana:2#Cake:3#Dog:4#Elephant:5#";
String strrep = str.replaceAll(":","#");
String splitted[] = strrep.split("#");
for (String i : splitted){
System.out.println(i);
}

public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your input: ");
String input = scanner.nextLine();
Arrays.stream(input.split("[:#]")).forEach(System.out::println);
}
}
This is the code that gets input for example Apple:1#Banana:2#Cake:3#Dog:4#Elephant:5 and it will split the input by # and : and print them line by line.
The result shown on the console will be like
Enter your input:
Apple:1#Banana:2#Cake:3#Dog:4#Elephant:5
Apple
1
Banana
2
Cake
3
Dog
4
Elephant
5
Or you can do with a simpler way without streams
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your input: ");
String input = scanner.nextLine();
for (int i = 0; i < input.length();) {
int nextHashIdx = input.indexOf("#", i);
if (nextHashIdx == -1) nextHashIdx = input.length();
String strWithColon = input.substring(i, nextHashIdx);
String[] strs = strWithColon.split(":");
System.out.println(strs[0]);
System.out.println(strs[1]);
i = nextHashIdx + 1;
}
}
}

Related

replace characters, one input multiple words

i have figured out a way to replace vowels into * but it only converts the first line
input:
break
robert
yeah
output:
br**k
here is the code
public class Solution {
public static void main(String[] args) {
String enterWord;
Scanner scan = new Scanner (System.in);
enterWord = scan.nextLine();
enterWord = enterWord.replaceAll("[aeiou]", "*");
System.out.println(enterWord);
}
}
is there any way that it reads all three words?
Your code works as you want (in:break robert yeah out: br**k r*b*rt y**h) on my env(Windows10, java1.8.0_271), maybe you can set a breakpoint on enterWord = enterWord.replaceAll("[aeiou]", "*"); and check is the enterWord recived whole input string.
You need a loop to keep getting and processing the inputs. Also, I suggest you use (?i) with the regex to make it case-insensitive.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String enterWord, answer = "y";
Scanner scan = new Scanner(System.in);
do {
System.out.print("Enter a word: ");
enterWord = scan.nextLine();
enterWord = enterWord.replaceAll("(?i)[aeiou]", "*");
System.out.println("After replacing vowels with * it becomes " + enterWord);
System.out.print("Do you wish to conntinue[y/n]: ");
answer = scan.nextLine();
} while (answer.equalsIgnoreCase("y"));
}
}
A sample run:
Enter a word: hello
After replacing vowels with * it becomes h*ll*
Do you wish to conntinue[y/n]: y
Enter a word: India
After replacing vowels with * it becomes *nd**
Do you wish to conntinue[y/n]: n
For a single string spanning multiple lines, the method, String#replaceAll works for the entire string as shown below:
public class Main {
public static void main(String[] args) {
String str = "break\n" +
"robert\n" +
"yeah";
System.out.println(str.replaceAll("(?i)[aeiou]", "*"));
}
}
Output:
br**k
r*b*rt
y**h
Using this feature, you can build a string of multiple lines interactively and finally change all the vowels to *.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String text = "";
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
System.out.println("Keep enter some text (Press Enter without any text to stop): ");
while (true) {
text = scan.nextLine();
if (text.length() > 0) {
sb.append(text).append(System.lineSeparator());
} else {
break;
}
}
System.out.println("Your input: \n" + sb);
String str = sb.toString().replaceAll("(?i)[aeiou]", "*");
System.out.println("After converting each vowel to *, your input becomes: \n" + str);
}
}
A sample run:
Keep enter some text (Press Enter without any text to stop):
break
robert
yeah
Your input:
break
robert
yeah
After converting each vowel to *, your input becomes:
br**k
r*b*rt
y**h

Taking first uppercase character of a multiple splitted string

So I want to print out the first uppercase character when splitting my String when it reaches a special character.
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
if(input.contains("-")){
for (int i = 0; i < input.length(); i++){
String[] parts = input.split("-",2);
String string1 = parts[0];
String string2 = parts[1];
System.out.print(string1.substring(0, 0) + string2.substring(0,0));
}
}
}
``
I'll give an example of what I'd like it to do.
> input: Please-WooRk-siR
> output: PW
> input: This-Is-A-Test
> output: TIAT
So only print the first uppercase character of each substring.
Any ideas? Thanks in advance :)
If you use regular expressions, you can use a zero-width negative lookahead to remove all characters that aren't capitals at the starts of words:
public static String capitalFirstLetters(String s) {
return s.replaceAll("(?!\\b[A-Z]).", "");
}
When you run the test cases:
public static void main(String[] args) throws Exception {
System.out.println(capitalFirstLetters("Please-WooRk-siR"));
System.out.println(capitalFirstLetters("This-Is-A-Test"));
}
It prints:
PW
TIAT
This is one way to do it.
String str = "This-Is-a-Test-of-The-Problem";
StringBuilder sb = new StringBuilder();
for (String s : str.split("-")) {
char c = s.charAt(0);
if (Character.isUpperCase(c)) {
sb.append(c);
}
}
System.out.println(sb.toString());
Update the code to this :
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
if (input.contains("-")) {
String[] parts = input.split("-");
for (String part: parts) {
System.out.print(Character.isUpperCase(part.charAt(0)) ? part.charAt(0) : "");
}
}
}
}
Output :
1.
Input : A-Ba
AB
2.
Input : A-aB
A
3.
Input : A
Now, your test case :
Input : This-Is-A-Test
TIAT
Another solution by utilizing javas streaming API
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
if (input.contains("-")) {
List<String> collect =
Stream.of(input.split("-")) // get a stream of words
.map(word -> word.substring(0, 1)) // get first character only
.filter(character -> character.toUpperCase().equals(character)) // only keep if character is uppercase
.peek(System.out::print) // print out character
.collect(Collectors.toList()); // just needed for stream to start
}
}

Accept different strings from user and display them using colon as separator using java

Which class should I use to get colon separator? I had tried using String.join(":",inputs[i]).This is my code:
import java.util.Scanner;
public class StringsColonSeparator {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String[] inputs = new String[5];
for (int i = 0; i < 5; i++) {
System.out.print("Enter a string: ");
inputs[i] = s.nextLine();
}
}
}
How to get output in form of:
name 1 : name 2 : name 3 : name 4 : name 5
The problem is that it looks that you are joining the Strings while looping (i.e. inside the for loop). You should use String.join after you have filled the array:
import java.util.Scanner;
public class StringsColonSeparator {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String[] inputs = new String[5];
for (int i = 0; i < 5; i++) {
System.out.print("Enter a string: ");
inputs[i] = s.nextLine();
}
System.out.println(String.join(" : ", inputs)); // join after you fill the array
}
}
Run output:
Enter a string: name 1 Enter a string: name 2 Enter a string:
name 3 Enter a string: name 4 Enter a string: name 5 name
1 : name 2 : name 3 : name 4 : name 5

Java: How to enter multiple values on the same line?

This is my code:
package assignment.pkg1;
import java.util.Scanner;
public class Exercise3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter three integers: ");
byte t1 = scan.nextByte() , t2 = scan.nextByte(), t3 = scan.nextByte(); }
/* I'm getting this result for example:
Enter three integers: 10
20
30
I want to get this result: 10 20 30 */
How can i get the three inputs on the same line?
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Use Regular Expressions, Pattern, and Matcher
String input = user_input.nextLine();
Pattern p = Pattern.compile("(\\d+)|([a-zA-Z]+)");
Matcher m = p.matcher(input);
List<String> nums = new LinkedList<String>();
while (m.find()) {
String num = m.group(1);
nums.add(num);
System.out.println(nums);
}
Take the input as a string. Use Regx and separate the string and get it into an array.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int length = 3;
System.out.print("Enter three integers: ");
String s = scan.nextLine();
String[] array = s.split("\\s", -1);
for (int i = 0; i<array.length;i++){
System.out.println(array[i]);
}
}
You can safely enter all three numbers in one line, the way you want.
You need to read the entire line as a String.
Then split the line on spaces into an array of Strings.
Then parse the strings into bytes.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter three integers: ");
String line = scanner.nextLine();
String[] numbers = line.split(" ");
byte t1 = Byte.valueOf(numbers[0]);
byte t2 = Byte.valueOf(numbers[1]);
byte t3 = Byte.valueOf(numbers[2]);
Keep in mind that you shouldn't press return until after you have entered the 3rd number.

Java: how to print a dataset of strings as entered except in reverse order?

This program should input a dataset of names followed by the name "END". The program should print out the list of names in the dataset in reverse order from which they were entered. What I have works, but if I entered "Bob Joe Sally Sue" it prints "euS yllaS eoJ boB" insead of "Sue Sally Joe Bob". Help!?
import java.util.Scanner;
public class ReverseString {
public static void main(String args[]) {
String original, reverse = "";
Scanner kb = new Scanner(System.in);
System.out.println("Enter a list of names, followed by END:");
original = kb.nextLine();
int length = original.length();
while (!original.equalsIgnoreCase("END") ) {
for ( int i = length - 1; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
original = kb.next();
}
System.out.println("Reverse of entered string is: "+reverse);
}
}
I think that you need to use this simple algorithm. Actually you're not using the proper approach.
Take the whole string which contains all the names separated by spaces;
Split it using as a delimiter the space (use the method split)
After the split operation you will get back an array. Loop through it from the end (index:array.length-1) to the starter element (1) and save those elements in another string
public String reverseLine(String currLine) {
String[] splittedLine = currLine.split(" ");
StringBuilder builder = new StringBuilder("");
for(int i = splittedLine.length-1; i >= 1; i--) {
builder.append(splittedLine[i]).append(" ");
}
return builder.toString();
}
I've supposed that each lines contains all the names separated by spaces and at the end there is a string which is "END"
A quick way, storing the result in the StringBuilder:
StringBuilber reverse = new StringBuilder();
while (!original.equalsIgnoreCase("END")) {
reverse.append(new StringBuilder(original).reverse()).append(" ");
original = kb.next();
}
System.out.println("Reverse: " + reverse.reverse().toString());
Using the approach suggested in the comments above is very simple, and would look something like:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> names = new ArrayList<>();
while (sc.hasNext())
{
String name = sc.next();
if (name.equals("END"))
{
break;
}
names.add(name);
}
Collections.reverse(names);
for (String name: names)
{
System.out.println(name);
}
System.out.println("END");
}
Let the Scanner extract the tokens for you, no need to do it yourself.

Categories