I have a string like:
(aeiou 123) word one
How can I remove everything from the parenthesis so that only "word one" remains?
You could use a regex, e.g.:
String str = "(aeiou 123) word one";
str = str.replaceAll("\\([^\\)]*\\)", "").trim();
public class ParanthesisRemoval {
public static void main(String args[])
{
String test="ab(xy)cd(zw)ef";
boolean modified = true;
while(modified)
{
modified = false;
int indexOpenParanthesis = test.indexOf("(");
int indexClosedParanthesis = test.indexOf(")");
if(indexOpenParanthesis!=-1 && indexClosedParanthesis!=-1 && indexOpenParanthesis<indexClosedParanthesis)
{
int stringLength = test.length();
test = test.substring(0, indexOpenParanthesis)+test.substring(indexClosedParanthesis+1, stringLength);
modified=true;
}
}
System.out.println(test);
}
}
note that this will not work for nested parantesis - (()), or paranthesis not properly paired (()
Related
Here's the code that I attempted
public String isPalindrome(String s) {
String trimmed = s.replaceAll("[^A-Za-z0-9]", "");
String reversed = "";
int len = trimmed.length();
for (int i = len - 1; i >= 0; i--) {
char[] allChars = trimmed.toCharArray();
reversed += allChars[i];
}
if (trimmed.equalsIgnoreCase(reversed)) {
return "true";
} else {
return "false";
}
}
Sample Input 1
A man, a plan, a canal: Panama
Sample Output 1
true
Explanation 1
The given string is palindrome when considering only alphanumeric characters.
Sample Input 2
race a car
Sample Output 2
false
Explanation 2
The given string is not a palindrome when considering alphanumeric characters.
Your variable len comes from the length of the String s. But you use the value on the array coming from trimmed.
So if you want to remove the IndexOutOfBoundsException you should change your len declaration to:
int len = trimmed.length();
You can return boolean instead of String:
public static boolean isPalindrome(String s) {
String trimmed = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
int from = 0, to = trimmed.length() - 1;
while (from < to) {
if (trimmed.charAt(from) != trimmed.charAt(to)) {
return false;
}
from++;
to--;
}
return true;
}
You can use StringBuilder to reverse a String:
public static void main(String[] args) {
String input = "a#b!b^a";
String clean = input.replaceAll("[^A-Za-z0-9]", "");
String reverse = new StringBuilder(clean).reverse().toString();
boolean isPalindrome = reverse.equals(clean);
System.out.println(isPalindrome);
}
You can do like this in linear time as the loops are driven by the presence of non-alphabetic/digit characters. Also, no trimming or reversal of the string is required.
String[] test = {"A man, a plan, a canal: Panama",
"race a car","foobar", "ABC2CEc2cba"};
for (String s : test) {
System.out.printf("%5b -> %s%n", isPalindrome(s), s);
}
prints
true -> A man, a plan, a canal: Panama
false -> race a car
false -> foobar
true -> ABC2CEc2cba
The outer while loop drives then entire process until the indices cross or are equal. The inner loops simply skip over non-alphabetic/digit characters.
public static boolean isPalindrome(String s) {
int k = s.length() - 1;
int i = 0;
char c1 = '#';
char c2 = '#';
while (i <= k) {
while (!Character.isLetterOrDigit(c1 = s.charAt(i++)));
while (!Character.isLetterOrDigit(c2 = s.charAt(k--)));
if (Character.toLowerCase(c1) != Character.toLowerCase(c2)) {
return false;
}
}
return true;
}
I'm currently learning on how to manipulate strings and i think it'll take awhile for me to get used to it. I wanted to know how to capitalize a letter after a period in each sentence.
The output is like this:
Enter sentences: i am happy. this is genius.
Capitalized: I am happy. This is genius.
I have tried creating my own code but its not working, feel free to correct and change it. Here is my code:
package Test;
import java.util.Scanner;
public class TestMain {
public static void main(String[]args) {
String sentence = getSentence();
int position = sentence.indexOf(".");
while (position != -1) {
position = sentence.indexOf(".", position + 1);
sentence = Character.toUpperCase(sentence.charAt(position)) + sentence.substring(position + 1);
System.out.println("Capitalized: " + sentence);
}
}
public static String getSentence() {
Scanner hold = new Scanner(System.in);
String sent;
System.out.print("Enter sentences:");
sent = hold.nextLine();
return sent;
}
}
The tricky part is how am i gonna capitalize a letter after the period(".")? I don't have a lot of string manipulation knowledge so I'm really stuck in this area.
Try this:
package Test;
import java.util.Scanner;
public class TestMain {
public static void main(String[]args){
String sentence = getSentence();
StringBuilder result = new StringBuilder(sentence.length());
//First one is capital!
boolean capitalize = true;
//Go through all the characters in the sentence.
for(int i = 0; i < sentence.length(); i++) {
//Get current char
char c = sentence.charAt(i);
//If it's period then set next one to capital
if(c == '.') {
capitalize = true;
}
//If it's alphabetic character...
else if(capitalize && Character.isAlphabetic(c)) {
//...we turn it to uppercase
c = Character.toUpperCase(c);
//Don't capitalize next characters
capitalize = false;
}
//Accumulate in result
result.append(c);
}
System.out.println(result);
}
public static String getSentence(){
Scanner hold = new Scanner(System.in);
String sent;
System.out.print("Enter sentences:");
sent = hold.nextLine();
return sent;
}
}
What this is doing it advancing sequentially through all of the characters in the string and keeping state of when the next character needs to be capitalized.
Follow the comments for a deeper exaplanations.
You could implement a state machine:
It starts in the capitalize state, as each character is read it emits it and then decides what state to go to next.
As there are just two states, the state can be stored in a boolean.
public static String capitalizeSentence(String sentence) {
StringBuilder result = new StringBuilder();
boolean capitalize = true; //state
for(char c : sentence.toCharArray()) {
if (capitalize) {
//this is the capitalize state
result.append(Character.toUpperCase(c));
if (!Character.isWhitespace(c) && c != '.') {
capitalize = false; //change state
}
} else {
//this is the don't capitalize state
result.append(c);
if (c == '.') {
capitalize = true; //change state
}
}
}
return result.toString();
}
Here is solution with regular expressions:
public static void main(String[]args) {
String sentence = getSentence();
Pattern pattern = Pattern.compile("^\\W*([a-zA-Z])|\\.\\W*([a-zA-Z])");
Matcher matcher = pattern.matcher(sentence);
StringBuffer stringBuffer = new StringBuffer("Capitalized: ");
while (matcher.find()) {
matcher.appendReplacement(stringBuffer, matcher.group(0).toUpperCase());
}
matcher.appendTail(stringBuffer);
System.out.println(stringBuffer.toString());
}
Seems like your prof is repeating his assignments. This has already been asked:
Capitalize first word of a sentence in a string with multiple sentences
Use a pre-existing lib:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html#capitalize(java.lang.String,%20char...)
and guava
public static void main(String[] args) {
String sentences = "i am happy. this is genius.";
Iterable<String> strings = Splitter.on('.').split(sentences);
List<String> capStrings = FluentIterable.from(strings)
.transform(new Function<String, String>()
{
#Override
public String apply(String input){
return WordUtils.capitalize(input);
}
}).toList();
System.out.println(Joiner.on('.').join(capStrings));
}
Just use
org.apache.commons.lang3.text.WordUtils.capitalizeFully(sentence);
You can use below code to capitalize first letter after period in
each sentence.
String input = "i am happy. this is genius.";
String arr[] = input.split("\\.");
for (int i = 0; i < arr.length; i++) {
System.out.print(Character.toUpperCase(arr[i].trim().
charAt(0)) + arr[i].trim().substring(1) + ". ");
}
I'd go for regex as it is fast to use:
Split your string by ".":
String[] split = input.split("\\.");
Then capitalize the first letter of the resulting substrings and reunite to result string. (Be careful for spaces between periods and letters, maybe split by "\. "):
String result = "";
for (int i=0; i < split.length; i++) {
result += Character.toUpperCase(split[i].trim());
}
System.out.println(result);
Should do it.
The correct method to do it with core java using regex will be
String sentence = "i am happy. this is genius.";
Pattern pattern = Pattern.compile("[^\\.]*\\.\\s*");
Matcher matcher = pattern.matcher(sentence);
String capitalized = "", match;
while(matcher.find()){
match = matcher.group();
capitalized += Character.toUpperCase(match.charAt(0)) + match.substring(1);
}
System.out.println(capitalized);
Try this:
1. Capitalize the first letter.
2. If the character is '.' set the flag true so that you can capitalize the next character.
public static String capitalizeSentence(String str)
{
if(str.length()>0)
{
char arr[] = str.toCharArray();
boolean flag = true;
for (int i = 0; i < str.length(); i++)
{
if (flag)
{
if (arr[i] >= 97 && arr[i] <= 122)
{
arr[i] = (char) (arr[i] - 32);
flag = false;
}
} else
{
if (arr[i] == '.')
flag = true;
}
}
return new String(arr);
}
return str;
}
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
I'm trying to create a method that will accept 2 strings as arguments. The first string will be a phrase, the second also a prhase. What I want the method to do is to compare both strings for matching chars. If string 2 has a char that is found in string 1 then replace string 2's instance of the char with an underscore.
Example:
This is the input:
phrase1 = "String 1"
phrase2 = "Strone 2"
The output string is called newPhrase and it will have the string built from the underscores:
newPhrase = "___one 2"
Its not working for me I am doing something wrong.
public class DashedPhrase
{
public static void main(String[] args)
{
dashedHelp("ABCDE","ABDC");
}
public static String dashedHelp(String phrase1, String phrase2)
{
String newPhrase = "_";
for(int i = 0; i < phrase.length(); i++)
{
if(phrase.charAt(i) == phrase2.charAt(i))
{
newPhrase.charAt(i) += phrase2.charAt(i);
}
}
System.out.print(newPhrase);
return newPhrase;
}
}
To make it easier for you to understand, you can use StringBuilder and its method setCharAt().
Notice the i < phrase1.length() && i < phrase2.length() in the condition for the for loop. This is to make sure you don't get any ArrayIndexOutOfBounds exception.
public static void main(String[] args)
{
System.out.println("ABCDE");
System.out.println("ABDC");
dashedHelp("ABCDE","ABDC");
System.out.println();
System.out.println();
System.out.println("String 1");
System.out.println("Strone 2");
String phrase1 = "String 1";
String phrase2 = "Strone 2";
dashedHelp(phrase1, phrase2);
}
public static String dashedHelp(String phrase1, String phrase2)
{
StringBuilder newPhrase = new StringBuilder(phrase1);
for(int i = 0; i < phrase1.length() && i < phrase2.length(); i++)
{
if(phrase1.charAt(i) == phrase2.charAt(i))
{
newPhrase.setCharAt(i, '_');
}
}
System.out.print(newPhrase);
return newPhrase.toString();
}
Output:
ABCDE
ABDC
__CDE
String 1
Strone 2
___i_g_1
newPhrase.charAt(i) doesn't let you replace a character, it just returns it. Java's Strings are immutable. I you want to change it you should use StringBuilder. Look into the replace(int start, int end, String str) method.
Since you need to return a string that has the same length as phrase2, you need to iterate over each character of phrase2, and replace the matching characters of both phrases. And, of course, if phrase2 is longer than phrase1, you need to include the remaining characters in the answer. You can try this:
public static String dashedHelp(String phrase1, String phrase2) {
String ans = "";
String subChar = "_";
int i;
for(i = 0; i<phrase2.length(); i++) {
if(i<phrase1.length() && phrase1.charAt(i) == phrase2.charAt(i))
ans += subChar;
else
ans += phrase2.charAt(i);
}
return ans;
}
Hope it helps
Of course, if you need to output phrase1 with underscores in the places where phrase2 has equal characters, you can interchange phrase2 with phrase1 in the above code.
Testing it
The complete class would look like this:
public class MyClass {
public static String dashedHelp(String phrase1, String phrase2) {
// The method code goes here
}
public static void main(String[] args) {
System.out.println(dashedHelp("String 1", "Strone 2"));
}
}
The output of this program is ___o_e_2. This matches (approximately) your desired output.
The code in the example won't even compile.
newPhrase.charAt(i) += phrase2.charAt(i);
That's a bad assignment. It's the same as writing
newPhrase.charAt(i) = newPhrase.charAt(i) + phrase2.charAt(i);
but the expression on the left side of the '=' isn't something to which you can properly assign a value.
How can I check to see if a String contains a whitespace character, an empty space or " ". If possible, please provide a Java example.
For example: String = "test word";
For checking if a string contains whitespace use a Matcher and call its find method.
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();
If you want to check if it only consists of whitespace then you can use String.matches:
boolean isWhitespace = s.matches("^\\s*$");
Check whether a String contains at least one white space character:
public static boolean containsWhiteSpace(final String testCode){
if(testCode != null){
for(int i = 0; i < testCode.length(); i++){
if(Character.isWhitespace(testCode.charAt(i))){
return true;
}
}
}
return false;
}
Reference:
Character.isWhitespace(char)
Using the Guava library, it's much simpler:
return CharMatcher.WHITESPACE.matchesAnyOf(testCode);
CharMatcher.WHITESPACE is also a lot more thorough when it comes to Unicode support.
This will tell if you there is any whitespaces:
Either by looping:
for (char c : s.toCharArray()) {
if (Character.isWhitespace(c)) {
return true;
}
}
or
s.matches(".*\\s+.*")
And StringUtils.isBlank(s) will tell you if there are only whitepsaces.
Use Apache Commons StringUtils:
StringUtils.containsWhitespace(str)
public static void main(String[] args) {
System.out.println("test word".contains(" "));
}
You could use Regex to determine if there's a whitespace character. \s.
More info of regex here.
Use this code, was better solution for me.
public static boolean containsWhiteSpace(String line){
boolean space= false;
if(line != null){
for(int i = 0; i < line.length(); i++){
if(line.charAt(i) == ' '){
space= true;
}
}
}
return space;
}
You can use charAt() function to find out spaces in string.
public class Test {
public static void main(String args[]) {
String fav="Hi Testing 12 3";
int counter=0;
for( int i=0; i<fav.length(); i++ ) {
if(fav.charAt(i) == ' ' ) {
counter++;
}
}
System.out.println("Number of spaces "+ counter);
//This will print Number of spaces 4
}
}
String str = "Test Word";
if(str.indexOf(' ') != -1){
return true;
} else{
return false;
}
Maybe I'm late with the most updated answer. You can use one of the following solution:
public static boolean containsWhiteSpace(final String input) {
if (isNotEmpty(input)) {
for (int i = 0; i < input.length(); i++) {
if (Character.isWhitespace(input.charAt(i)) || Character.isSpaceChar(input.charAt(i))) {
return true;
}
}
}
return false;
}
or
public static boolean containsWhiteSpace(final String input) {
return CharMatcher.whitespace().matchesAnyOf(input);
}
import java.util.Scanner;
public class camelCase {
public static void main(String[] args)
{
Scanner user_input=new Scanner(System.in);
String Line1;
Line1 = user_input.nextLine();
int j=1;
//Now Read each word from the Line and convert it to Camel Case
String result = "", result1 = "";
for (int i = 0; i < Line1.length(); i++) {
String next = Line1.substring(i, i + 1);
System.out.println(next + " i Value:" + i + " j Value:" + j);
if (i == 0 | j == 1 )
{
result += next.toUpperCase();
} else {
result += next.toLowerCase();
}
if (Character.isWhitespace(Line1.charAt(i)) == true)
{
j=1;
}
else
{
j=0;
}
}
System.out.println(result);
Use org.apache.commons.lang.StringUtils.
to search for whitespaces
boolean withWhiteSpace = StringUtils.contains("my name", " ");
To delete all whitespaces in a string
StringUtils.deleteWhitespace(null) = null
StringUtils.deleteWhitespace("") = ""
StringUtils.deleteWhitespace("abc") = "abc"
StringUtils.deleteWhitespace(" ab c ") = "abc"
I purpose to you a very simple method who use String.contains:
public static boolean containWhitespace(String value) {
return value.contains(" ");
}
A little usage example:
public static void main(String[] args) {
System.out.println(containWhitespace("i love potatoes"));
System.out.println(containWhitespace("butihatewhitespaces"));
}
Output:
true
false
package com.test;
public class Test {
public static void main(String[] args) {
String str = "TestCode ";
if (str.indexOf(" ") > -1) {
System.out.println("Yes");
} else {
System.out.println("Noo");
}
}
}