I am attempting to split a word from its punctuation:
So for example if the word is "Hello?". I want to store "Hello" in one variable and the "?" in another variable.
Here is my code so far:
String inWord = "hello?";
if (inWord.contains(","+"?"+"."+"!"+";")) {
String parts[] = inWord.split("\\," + "\\?" + "\\." + "\\!" + "\\;");
String word = parts[0];
String punctuation = parts[1];
} else {
String word = inWord;
}
System.out.println(word);
System.out.println(punctuation);
My problem is that I am getting error: cannot find symbol when I try and print out the word and the punctuation.
Thanks for help in advance
There are other things wrong with your code but your question was why you get the 'cannot find symbol' error.
String inWord = "hello?";
String word;
String punctuation = null;
if (inWord.contains(","+"?"+"."+"!"+";")) {
String parts[] = inWord.split("\\," + "\\?" + "\\." + "\\!" + "\\;");
word = parts[0];
punctuation = parts[1];
} else {
word = inWord;
}
System.out.println(word);
System.out.println(punctuation);
The scope of a variable declaration like String word = ... is only the block (the pieces of code inside '{' and '}') that it's in. The variables word and punctuation don't exist in the scope in which you try to print them.
You need to declare your variables word and punctuation in the same scope (or an enclosing scope) of where you access them in your System.out.println
You made the following errors in your code.
1.Declare the string outside the if condition
2.inWord.contains(","+"?"+"."+"!"+";") this is equal to inword.contains(",?.!;") , so the condition will fail always and it goes to else condition
split() will not store the value based on which you split the string
eg
String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556
In this the value "-" can't be stored.Hope you understand what i'm trying to convey.
You could try with your custom contains function and StringTokenizer
as:
public class Test{
public static void main(String[] args) {
String inWord = "hello";
String[] wordAndPunctuation = null;
char[] punctuations =new char[]{',','?','.','!',';'};
StringTokenizer tokenizer = new StringTokenizer(inWord,new String(punctuations),true);
int i = 0;
if (Test.contains(inWord,punctuations)) {
while(tokenizer.hasMoreTokens()){
wordAndPunctuation = new String[tokenizer.countTokens()];
System.out.println(tokenizer.countTokens());
wordAndPunctuation[i] = tokenizer.nextToken();
i++;
}
}else{
System.out.println("No punctuation in "+inWord);
}
}
public static boolean contains(String str, char[] charArr){
System.out.println(Arrays.toString(charArr));
for(char c:charArr){
if(str.contains(String.valueOf(c)))
return true;
}
return false;
}
}
I would recommend parsing through the String and checking if the character is a punctuation method:
String sentence = "Hello? Is this Mrs. Doubtfire?"; // Example.
ArrayList<String> chunks = new ArrayList<>(); // Will store the "non-punctuated chunks"
ArrayList<Character> puncts = new ArrayList<>();// Will the punctuations in the "sentence"
char[] punctuations = {',','?','.','!',';'}; // Store punctuations here.
int lastIndex = 0;
for (int i = 0; i < sentence.length(); i++) {
char c = sentence.charAt(i);
for (char punctuation : punctuations) {
if (c == punctuation) {
chunks.add(sentence.substring(lastIndex, i).trim());
puncts.add(c);
lastIndex = i + 1;
}
}
}
System.out.println(chunks);
System.out.println(puncts);
Output:
[Hello, Is this Mrs, Doubtfire]
[?, ., ?]
And remember to import java.util.ArrayList!
Why don't you do this:
String s = "hello!";
Pattern p = Pattern.compile("(\\w+)?(\\W)");
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println("Word: " + m.group(1) + " | Punctuation: " + m.group(2));
}
Group1 will contain the word and Group2 will contain the punctuation.
Demo : http://ideone.com/ljIZFW
Related
My task is splitting a string, which starts with numbers and contains numbers and letters, into two sub-strings.The first one consists of all numbers before the first letter. The second one is the remained part, and shouldn't be split even if it contains numbers.
For example, a string "123abc34de" should be split as: "123" and "abc34de".
I know how to write a regular expression for such a string, and it might look like this:
[0-9]{1,}[a-zA-Z]{1,}[a-zA-Z0-9]{0,}
I have tried multiple times but still don't know how to apply regex in String.split() method, and it seems very few online materials about this. Thanks for any help.
you can do it in this way
final String regex = "([0-9]{1,})([a-zA-Z]{1,}[a-zA-Z0-9]{0,})";
final String string = "123ahaha1234";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
matcher.group(1) contains the first part and matcher.group(2) contains the second
you can add it to a list/array using these values
You can use a pretty simple pattern : "^(\\d+)(\\w+)" which capture digits as start, and then when letters appear it take word-char
String string = "123abc34de";
Matcher matcher = Pattern.compile("^(\\d+)(\\w+)").matcher(string);
String firstpart = "";
String secondPart = "";
if (matcher.find()) {
firstpart = matcher.group(1);
secondPart = matcher.group(2);
}
System.out.println(firstpart + " - " + secondPart); // 123 - abc34de
This is not the correct way but u will get the result
public static void main(String[] args) {
String example = "1234abc123";
int index = 0;
String[] arr = new String[example.length()];
for (int i = 0; i < example.length(); i++) {
arr = example.split("");
try{
if(Integer.parseInt(arr[i]) >= 0 & Integer.parseInt(arr[i]) <= 9){
index = i;
}
else
break;
}catch (NumberFormatException e) {
index = index;
}
}
String firstHalf = example.substring(0,Integer.parseInt(arr[index])+1);
String secondHalf = example.substring(Integer.parseInt(arr[index])+1,example.length());
System.out.println(firstHalf);
System.out.println(secondHalf);
}
Output will be: 1234 and in next line abc123
Expected Input: Doe, John
Expected Output: J. Doe
public static void main(String[] args) {
String z = "Doe, John";
System.out.println(z);
String y = formatName(name);
System.out.println(y);
}
public static String formatName(String name) {
String str[] = name.split(",");
StringBuilder sb = new StringBuilder();
sb.append(str[1].charAt(0));
sb.append(". ");
sb.append(str[0]);
return sb.toString();
}
My output is not as expected.
Match (Optional) White Space with String.split Regular Expression
You have a space after the comma in your input, you could modify your regular expression in split from
String str[] = name.split(",");
to
String str[] = name.split(",\\s*");
to match and remove optional white-space. After I made the above change I ran your code, and got the (expected) output
Doe, John
J. Doe
Trim the Leading White Space
Alternatively, you could trim str[1] before getting the first character like
sb.append(str[1].trim().charAt(0)); //<-- will also remove leading space
Regular Expression With a Compiled Pattern
Another possible option is compiling a regex Pattern and using a Matcher like
// Match (and group) one more characters followed by a "," and
// optional whitespace. Then match (and group) one character followed
// any number of optional characters.
private static Pattern pattern = Pattern.compile("(.+),\\s*(.).*");
public static String formatName(String name) {
Matcher m = pattern.matcher(name);
if (m.matches()) {
return String.format("%s. %s", m.group(2), m.group(1));
}
return name;
}
Another simple way to get FirstInitial.LastName
Other than using split, you can use substring and based on the position of the comma ,, manipulate the name to get the output:
String s = "Doe, John";
s = s.replace(" ", ""); //remove spaces
int i = s.indexOf(","); //get pos of comma
String name = s.charAt(i+1) + ". " + s.substring(0, i); //create name
Output:
J. Doe
sb.append(str[1].charAt(0)); , index for charAt() should be 1 not 0 .
String str[] = name.split(","); will return [Doe, John], notice the space before second element.
better yet use split(", ")
I tried this based on what i understood. Use for loop and trim the items
public static String formatName(String name) {
String str[] = name.split(",");
for(int i = 0 ; i < str.length ; i++){
str[i] = str[i].trim();
//System.out.println("+"+str[i]+"+");
}
StringBuilder sb = new StringBuilder();
sb.append(str[1].charAt(0));
sb.append(".");
sb.append(str[0]);
sb.append(".");
return sb.toString().trim();
}
I'm trying to make an encryptor.What i want it to do:
Get the text i enter and reverse the first two letters of every word
and then display it again.
I have tried a lot of ways.This is the last one i've tried:
private void TranslateToEf(){
String storage = Display.getText();
String[] arr = storage.split("\\W+");
for ( String ss : arr) {
char c[] = ss.toCharArray();
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String(c);
Display.appendText(swappedString + " ");
}
}
You may want to consider maintaining all the delimiters lost from the first String.split("\\W+") so they can be included in the final result. I would do that with a String.split("\\w+")
You may also want to consider that when you swap the first two letters, if the first letter is capital it becomes lowercase and the second letter becomes uppercase. Otherwise, just do a direct swap.
Code sample:
public static void main(String[] args) throws Exception {
String data = "Hello;World! My name is John. I write code.";
String[] words = data.split("\\W+");
String[] delimiters = data.split("\\w+");
int delimiterIndex = 0;
StringBuilder sb = new StringBuilder();
for (String word : words) {
if (word.length() < 2) {
sb.append(word);
} else {
char firstLetter = word.charAt(0);
char secondLetter = word.charAt(1);
if (Character.isUpperCase(firstLetter)) {
// Swap the first two letters and change casing
sb.append(Character.toUpperCase(secondLetter))
.append(Character.toLowerCase(firstLetter));
} else {
// Swap the first two letters
sb.append(secondLetter)
.append(firstLetter);
}
// Append the rest of the word past the first two letters
sb.append(word.substring(2));
}
// Append delimiters
if (delimiterIndex < delimiters.length) {
// Skip blank delimiters if there are any
while (delimiters[delimiterIndex].isEmpty()) {
delimiterIndex++;
}
// Append delimiter
sb.append(delimiters[delimiterIndex++]);
}
}
data = sb.toString();
// Display result
System.out.println(data);
}
Results:
Ehllo;Owrld! Ym anme si Ojhn. I rwite ocde.
public class Encrypto {
public static void main(String[] args) {
String input="Hello World";
String [] word = input.split(" ");
// System.out.println(word[0]);
String encryWord="";
for(int i=0;i<word.length;i++){
if (word[i].length() > 0) {
String tmp0 = String.valueOf(word[i].charAt(1));
String tmp1 = String.valueOf(word[i].charAt(0));
encryWord += tmp0.toLowerCase() + tmp1.toLowerCase() + word[i].substring(2) + " ";
}else{
encryWord +=word[i];
}
}
System.out.println(encryWord);
}
}
I think answer is more helpful for you
There are a few problems.
Declare zz outside the loop if you want to use it outside.
Append zz on every iteration. Not just assign it.
Something like this,
private void TranslateToEf(){
String storage = Display.getText();
String[] arr = storage.split("\\W+");
String zz = "";
for ( String ss : arr) {
char c[] = ss.toCharArray();
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String(c);
String b= " ";
zz += swappedString + b;
}
Display.setText(zz + " ");
}
You are splitting with non-word (\W+) characters, but replacing it only with a space " ". This could alter the string with special characters.
Not sure what exactly you are looking for but i little modification in your code see if this suits your needs
String storage = "Test test t";
String[] arr = storage.split("\\W+");
String abc = "";
for ( String ss : arr) {
if(ss.length() > 1)
{
char c[] = ss.toCharArray();
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String( c );
String b = " ";
String zz = swappedString + b;
abc = abc + zz;
}else{
abc = abc + ss;
}
}
System.out.println(abc);
In Java strings are immutable. You can't modify them "on the fly", you need to reassign them to a new instance.
Additionally, you are setting the last display text to zz, but zz is a local variable to your loop, and therefore it gets re-instantiated with every iteration. In other words, you would be assigning to display only the last word!
Here is what you have to do to make it work:
String storage = Display.getText();
String[] arr = storage.split("\\W+");
String[] newText = new String[arr.length];
for ( int i = 0; i<arr.length; i++) {
String original = arr[i];
String modified = ((char) original.charAt(1)) + ((char) original.charAt(0)) + original.substring(2);
newText[i] = modified;
}
//Join with spaces
String modifiedText = Arrays.asList(newText).stream().collect(Collectors.join(" "));
Display.setText(modifiedText);
Note that:
1) We are assuming all strings have at least 2 chars
2) that your splitting logic is correct. Can you think some edge cases where your regexp fails?
From the below URL, I am trying to extract 2 Strings i.e String a = "region/country"; and String b = "123xyz"; I tried using overloaded method of IndexOf but that too didnt help. Any pointers?
String URL = "http://abcd.com/region/country/state/123xyzCONSTANTTEXT.html";
You can use the Pattern class for this. If you want to match only the next two words after that url (that doesnt change) then you can use this. \w is a shorthand for [a-zA-Z0-9_]. If you are ok with _ then use \w or else use [a-zA-Z0-9].
The area inside the parenthesis is a matching group, if you want to separate out region and country simply put parenthesis around each of the \w individually and matcher.group(1) will contain region and matcher.group(2) will contain country
String URL = "http://abcd.com/region/country/state/123xyzCONSTANTTEXT.html";`
Pattern pattern = Pattern.compile("http://abcd.com/(\\w+/\\w+)");
Matcher matcher = pattern.matcher(URL);
if (matcher.find()) {
System.out.println(matcher.group(1)); //prints region/country
} else {
System.out.println("Match not found");
}
You could use the split() method. It takes one argument in the form of a regex string and outputs an array of strings, split around the regex.
String[] stringArray = URL.split("/");
Will probably output an array like:
String[] stringArray = {"http:","","abcd.com","region","country","state","123xyzCONSTANTTEXT.html"};
And then use split again on an array index:
String[] stringArray2 = stringArray[7].split("CONSTANTTEXT.html");
To retrieve 123xyz, which will be stored in stringArray2[0]
For example
public class Example {
public static void main(String[] args) {
String[] string = "http://abcd.com/region/country/state/123xyzCONSTANTTEXT.html".split("/");
String string1 = "";
String string2 = "";
for(int i =0; i < string.length ; i++) {
if(i == 3) {
string1 += string[i] + "/";
}
if(i == 4) {
string1 += string[i];
}
if(i == 6) {
string2 = string[i].substring(0, Math.min(string[i].length(), 6));
}
}
System.out.println(string1);
System.out.println(string2);
}
}
output:
region/country
123xyz
I need to convert a String value in to Upper case (First letter to upper in every word).
This can be done in php by using ucwords() method.
Ex :
String myString = “HI GUYS”;
myString = myString. toLowerCase().replaceAll(“Regex”, “Some Charactor”)
Thanks with hi5
Using regex, it will be difficult. Try following simple code:
String str="hello world";
String[] words=str.split(" ");
for (String word : words) {
char upCase=Character.toUpperCase(word.charAt(0));
System.out.print(new StringBuilder(word.substring(1)).insert(0, upCase));
}
Output:
Hello World
Undermentioned will work great in all your situation
If you need to get first letter of all words capital ..
-----------------------------------------------------
public String toTheUpperCase(String givenString) {
String[] arr = givenString.split(" ");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
sb.append(Character.toUpperCase(arr[i].charAt(0)))
.append(arr[i].substring(1)).append(" ");
}
return sb.toString().trim();
}
When you need first letter of first word to be capitalized
-------------------------------------------------------------
public String toTheUpperCaseSingle(String givenString) {
String example = givenString;
example = example.substring(0, 1).toUpperCase()
+ example.substring(1, example.length());
System.out.println(example);
return example;
}
How to use :: Try defining this code n your super class ( Best code practice )
Now when u need to use this method .. just pass String which you need to transform .
For Ex:: Let us assume our super class as CommanUtilityClass.java ...
Now you need this method in some activity say " MainActivity.java "
Now create object of super class as :: [ CommanUtilityClass cuc; ]
Final task -- use this method as described below:
your_text_view.setText(cuc.toTheUpperCase(user_name)); // for all words
your_text_view.setText(cuc.toTheUpperCaseSingle(user_name)); // for only first word ...
Let me know if you need more details for that ..
Enjoy
Cheers !
System.out.println(ucWord("the codes are better than words !!"));// in main method
private static String ucWord(String word) {
word = word.toLowerCase();
char[] c = word.toCharArray();
c[0] = Character.toUpperCase(c[0]);
int len = c.length;
for (int i = 1; i < len; i++) {
if (c[i] == ' ') {
i++;
c[i] = Character.toUpperCase(c[i]);
}
}
return String.valueOf(c);
}
You can use WordUtils from apache for same purpose,
WordUtils.capitalizeFully(Input String);
Here are simplified versions of the toUpperCase methods.
Change all first letters in the sentence to upper case.
public static String ucwords(String sentence) {
StringBuffer sb = new StringBuffer();
for (CharSequence word: sentence.split(" "))
sb.append(Character.toUpperCase(word.charAt(0))).append(word.subSequence(1, word.length())).append(" ");
return sb.toString().trim();
}
Change only the first word to upper case. (nice one-liner)
public static String ucFirstWord(String sentence) {
return String.valueOf(Character.toUpperCase(word.charAt(0))).concat(word.substring(1));
}
String stringToSearch = "this string is needed to be first letter uppercased for each word";
// First letter upper case using regex
Pattern firstLetterPtn = Pattern.compile("(\\b[a-z]{1})+");
Matcher m = firstLetterPtn.matcher(stringToSearch);
StringBuffer sb = new StringBuffer();
while(m.find()){
m.appendReplacement(sb,m.group().toUpperCase());
}
m.appendTail(sb);
stringToSearch = sb.toString();
sb.setLength(0);
System.out.println(stringToSearch);
output:
This String Is Needed To Be First Letter Uppercased For Each Word