suppose we have
String str = "Hello-Hello1";
How do we split it and compare it to see if it is equal or not?
This is what I wrote, but it does not give me the result.
public static void main(String[] args) {
String str = "Hello-Hello1";
String [] a = str.split("-");
for(int i=0; i<a.length; i++) {
System.out.print(a[i]+ " ");
}
for(int first =0; first<a.length; first++) {
for(int second =first+1; second<a.length; second ++) {
if(a[first].equals(a[second])){
System.out.println(a[first]);
}
}
}
}
First, you split your string like shown here:
How to split a string in Java, then compare them using the equals method: a[0].equals(a[1]);
Thank you all for helping
Here is the answer
public class SplitStringAndCompare {
public static void main(String[] args) {
String str = "Hello-Hello1";
String [] a = str.split("-");
if(a[0].equals(a[1])) {
System.out.println(a[0]+ " is equal to " + a[1]);
} else {
System.out.println(a[0]+ " is not equal to "+ a[1]);
}
}
Related
I am a student trying to get this palindrome checker to reflect back if the entered strings are indeed a palindrome or not. I keep returning just one result and I cannot figure out why. Not sure if I am missing something from my loop or if I have something incorrect in my loop here.
public class Palindrome {
public static void main(String[] args) {
System.out.println("Palindrome Checker: ");
palindromChecker("aabaa", "cat", "racecar", "dog", "Madam");
}
public static void palindromChecker(String... values) {
String stbr = "";
String reverse = " ";
for (int i = stbr.length() - 1; i >= 0; i--)
reverse += stbr.charAt(i);
if (reverse.equalsIgnoreCase(stbr))
System.out.println("This is a Palindrome");
else {
System.out.println("This is NOT a Palindrome");
}
}
}
You aren't actually looping through the input values from your array values. What you are doing is trying to reverse stbr which you assigned to be an empty String. You want to do something like this:
public class Palindrome {
public static void main(String[] args) {
System.out.println("Palindrome Checker: ");
palindromChecker("aabaa", "cat", "racecar", "dog", "Madam");
}
public static void palindromChecker(String... values) {
for (String stbr : values) {
String reverse = "";
for (int i = stbr.length() - 1; i >= 0; i--) {
reverse += stbr.charAt(i);
}
if (reverse.equalsIgnoreCase(stbr)) {
System.out.println("This is a Palindrome");
} else {
System.out.println("This is NOT a Palindrome");
}
}
}
}
for (String stbr : values) { loops through every element in values one at a time, allowing you to reverse and check each element of your input.
I want to separate words and print them in a single line with a hyphen(-) in between. I have written the following code but it only prints the last word followed by a hyphen i.e. the output is carrot-. I don't understand why and what changes do I make to get the desired output?
public class SeparatingWords {
public static void main(String[] args) {
String str = "apple banana carrot";
System.out.println(separatingWords(str));
}
public static String separatingWords(String str) {
String[] words = str.split(" ");
String result = null;
for (int i = 0; i < words.length; i++) {
result=words[i]+"-";
}
return result;
}
}
Instead of calling a split and concatenating the string, why can't you directly call replaceAll directly to achieve your goal. This will make your code simple.
String result = str.replaceAll(" ", "-");
Below is sample modified code of yours. Hope this helps
public class Sample {
public static void main(String[] args) {
String str = "apple banana carrot";
System.out.println(separatingWords(str));
}
public static String separatingWords(String str) {
String result = str.replaceAll(" ", "-");
return result;
}
}
If you want to perform any other operation based on your requirement inside the method, then below should work for you. As suggested by #Moler added += and initialized the result object
public static String separatingWords(String str) {
String[] words = str.split(" ");
String result = ""; // Defaulted the result
for (int i = 0; i < words.length-1; i++) {
result += words[i] + "-"; // Added a +=
}
result += words[words.length - 1];
return result;
}
public class SeparatingWords
{
public static void main(String[] args)
{
String str="apple banana carrot";
System.out.println(separatingWords(str));
}
public static String separatingWords(String str)
{
String[] words=str.split(" ");
String result="";
for(int i=0;i<words.length;i++)
{
result += words[i]+"-";
}
return result;
}
}
Try this code:
public class SeparatingWords
{
public static void main(String[] args)
{
String str="apple banana carrot";
System.out.println(separatingWords(str));
}
public static String separatingWords(String str)
{
String[] words=str.split(" ");
String result=words[0];
for(int i=1;i<words.length;i++)
{
result=result+"-"+words[i];
}
return result;
}
}
You could use s StringBuilder, append the single word and a hyphon and at the last word, you just append the word:
public class SeparatingWords {
public static void main(String[] args) {
String str = "apple banana carrot";
System.out.println(separatingWords(str));
}
public static String separatingWords(String str) {
String[] words = str.split(" ");
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < words.length; i++) {
resultBuilder.append(words[i]);
if (i != words.length - 1) {
resultBuilder.append("-");
}
}
return resultBuilder.toString();
}
}
String[] words = str.split(" ");
// perform operations on individual words
return String.join("-", words);
I am trying to find all possible options of combining a string array with two elements. Let's say, the array has two elements {"we","are"}. The output should be:"we" "are" "we are" "are we"
I could manage, with some search, to put together this code:
public class Main {
public static void main(String[] args) {
String[] strings = {"we", "are"};
final int maxbit = 1 << strings.length;
for (int p = 0; p < maxbit; p++) {
String finalString = "";
for (int i = 0; i < strings.length; i++) {
if ((1 << i & p) > 0) {
finalString += strings[i] + " ";
}
}
System.out.println(finalString);
}
}
My problem is, that I am missing one solution, the output is following: "we" "are" "we are".
So I am missing the "are we" option, would I need to use recursion to solve this problem or can this code be modified to show the remaining option?
UPDATE: solution found with the help of answers
public static void main(String[] args) {
String[] test = { "are", "we"};
language(test.length, test, "");
}
private static void language(final int n, final String[] syllables, final String currentWord) { // example of N = 3
if (n == 0) {
System.out.println(currentWord);
} else {
for (int i = 0; i < syllables.length; i++) {
if (currentWord.equals(syllables[i])){
language(n - 1, syllables, "" + syllables[i]);
}else{
language(n - 1, syllables, currentWord + syllables[i]);
}
}
}
}
Another example
import java.util.Arrays;
public class HelloWorld{
public static void main(String[] args) {
String[] strings = {"we", "are"};
String str = Arrays.toString(strings);
System.out.println("Java String array to String = "+str.replace(",","").replace("[","").replace("]",""));
}
}
I looked over it for a while, and found 2 ways to make it based on your code:
this will print out every permutation once, and DOESN'T have to include all the words:
public static void recPerm(String... input) {
recHelper(input, input.length, "");
}
private static void recHelper(String[] input, int length, String currentWord) {
if (currentWord != "")
System.out.println(currentWord);
for (int i = 0; i < input.length; i++) {
if (!currentWord.contains(input[i]))
recHelper(input, length - 1, currentWord + input[i]);
}
}
this will print out every permutation once, and DOES have to include all the words:
public static void maxRecPerm(String... input) {
maxRecHelper(input, input.length, "");
}
private static void maxRecHelper(String[] input, int length, String currentWord) {
if (length == 0)
System.out.println(currentWord);
for (int i = 0; i < input.length; i++) {
if (!currentWord.contains(input[i]))
maxRecHelper(input, length - 1, currentWord + input[i]);
}
}
I need "args[i]" to be converted to Uppercase so the output will be:
"$ARG1" line break
"$ARG2" line break
"$ARG3" line break
and so on. I need to use the "toUpperCase" method but don't know how.
public class Main {
public static void main(String[] args) {
System.out.println("Number of args:" +
args.length);
for(int i=0; i<args.length; i++){
char dollar = '\u0024';
System.out.println(dollar + args[i]);
}
}
}
Java has this functionality built into the String object like so:
System.out.println(dollar + args[i].toUpperCase());
See the Oracle documentation here
Just use .toUpperCase() on any String, and it will return an all-upper-case String.
System.out.println(dollar + args[i].toUpperCase());
java has String method :public String toUpperCase()
public class Main {
public static void main(String[] args) {
System.out.println("Number of args:" + args.length);
for(int i=0; i<args.length; i++){
char dollar = '\u0024';
System.out.println(dollar + args[i].toUpperCase());
}
}
}
See the Oracle documentation here
public class Main {
public static void main(String[] args) {
System.out.println("Number of args:" +
args.length);
char dollar = '\u0024';
for(int i=0; i<args.length; i++){
System.out.println(dollar + args[i].toUpperCase());
}
}
}
say I'm given a set of strings that looks like this:
0,test0,dummy
1,test,dummy
2,test1,dummy
3,test2,dummy
4,test3,dum,dum,dummy
I wrote code that can return only what's before the last ",":
public class RandomTest {
public static void main(String[] args) {
String testFile = "synsets11.txt";
In testIn = new In(testFile);
while (testIn.hasNextLine()) {
String line = testIn.readLine();
String result = line.substring(0, line.lastIndexOf(","));
List<String> synList = Arrays.asList(result.split(","));
for (String i : synList) {
System.out.println(i);
}
}
}
}
What I intended to do was only return the part of the string that was between the first and second "," characters, so my code above doesn't work for the last line of text. How do I only return what's between the first and second comma?
In this case, only test0, test, test1, test2, and test3.
thanks!
use split() method like this :
public static void main(String[] args) {
String s = "0,prop,dummy";
System.out.println(s.split(",")[1]);
}
O/P:
prop
NOTE : You have to check whether the String contains atleast 1 , (unless you want an ArrayIndexOutOfBoundsException :P)
Rather than using lastIndexOf, use indexOf twice:
int pos = line.indexOf(',', line.indexOf(',')+1);
String result = line.substring(0, pos);
You could use string.replaceAll function.
string.replaceAll("(?m)^[^,]*,|,.*", "");
DEMO
String s = "0,test0,dummy\n" +
"1,test,dummy\n" +
"2,test1,dummy\n" +
"3,test2,dummy\n" +
"4,test3,dum,dum,dummy";
System.out.println(s.replaceAll("(?m)^[^,]*,|,.*", ""));
What about StringTokenizer?
public class RandomTest {
public static void main(String[] args) {
String testFile = "synsets11.txt";
In testIn = new In(testFile);
StringTokenizer stok = null;
while (testIn.hasNextLine()) {
String line = testIn.readLine();
stok = new StringTokenizer(line,",");
for(int i = 0; i< stok.countTokens() ; i++){
String str = st.nextToken();
if( i == 1){
System.out.println(str);
}else if( i > 1){break;}
}// for
}// while
}//main
}//class