I have :
String word = "It cost me 500 box
What I want to do is to display this sentence like this :
It cost me
500 box
I need a general methode, not only for this example.
Can you helpe me please ?
As suggested you can use regular expression to do this job below is a code snippet that can do the trick for you:
String word = "It cost me 500 box";
Pattern p = Pattern.compile("(.* )([0-9].*)");
Matcher m = p.matcher(word);
if(m.matches()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
}
Hope this helps.
Not the optimum way but an easy one:
On top of your Activity:
String finalText="";
public static boolean isNumber(String string)
{
try
{
double d = Double.parseDouble(string);
}
catch(NumberFormatException e)
{
return false;
}
return true;
}
In your code:
String word = "It cost me 500 box";
for (int i=0 ; i<word.length() ; i++){
String a = Character.toString(word.charAt(i));
if (isNumber(a)){
finalText+="\n";
for (int j=i ; j<word.length() ; j++){
String b = Character.toString(word.charAt(j));
finalText+=b;
}
i = word.length();
}
else{
finalText+=a;
}
}
textView.setText(finalText);
I don't know if there are anymore inbuilt functions that I know of, but one way of doing this would be:
void match(String string) {
int numIndex = -1;
int charIndex = 0;
if (string.length() > 0) {
while (numIndex == -1 && charIndex < string.length()) {
if (Character.isDigit(string.charAt(charIndex)))
numIndex = charIndex;
charIndex++;
}
}
if (numIndex != -1) {
System.out.println(string.substring(0, numIndex));
System.out.println(string.substring(numIndex));
}
}
Related
I have inputs like "Test1","Test2"... and I just try to find end number in these strings. I wrote below code but I don't like it. How can I improve this code? Is there any advice?
private int getEndNumber(final String str) {
if (str.endsWith("1")) {
return 1;
} else if (str.endsWith("2")) {
return 2;
} else if (str.endsWith("3")) {
return 3;
} else if (str.endsWith("4")) {
return 4;
} else if (str.endsWith("5")) {
return 5;
} else if (str.endsWith("6")) {
return 6;
} else if (str.endsWith("7")) {
return 7;
} else {
return 0;
}
}
One liner - return last character:
return Integer.parseInt(str.substring(str.length() - 1)));
If you want to return 0 also when ends with 8 or 9 you will need to add a bit logic to it
Regex is your friend.
Pattern p = Pattern.compile("[0-9]+$"); // This regex matches the last number
Matcher m = p.matcher(str); // Create the matcher
//If the pattern matches then we get the matching string
if(m.find()) {
result = m.group();
}
You can alternatively iterate the string in reverse and check if the characters are integers, but that's rather tedious than using regexes.
There's a nice article about regexes here http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
You read it thoroughly and forget everything in a few days, like the most of us :-).
Extension from #user7294900 but multi-liner.
In case you do not want to use regex.
private int getEndNumber(final String str) {
Integer num = 0;
try {
num = Integer.parseInt(str.substring(str.length() - 1)) ;
num = num >= 7 ? 0 : num;
} catch (NumberFormatException ex) {
num = 0;
}
return num;
}
I am new to java programming. I want to print a string with alternate characters in UpperCase.
String x=jTextField1.getText();
x=x.toLowerCase();
int y=x.length();
for(int i=1;i<=y;i++)
{}
I don't know how to proceed further. I want to do this question with the help of looping and continue function.
Help would be appreciated. Thanks.
#Test
public void alternateUppercase(){
String testString = "This is a !!!!! test - of the emergency? broadcast System.";
char[] arr = testString.toLowerCase().toCharArray();
boolean makeUppercase = true;
for (int i=0; i<arr.length; i++) {
if(makeUppercase && Character.isLetter(arr[i])) {
arr[i] = Character.toUpperCase(arr[i]);
makeUppercase = false;
} else if (!makeUppercase && Character.isLetter(arr[i])) {
makeUppercase = true;
}
}
String convertedString = String.valueOf(arr);
System.out.println(convertedString);
}
First, java indexes start at 0 (not 1). I think you are asking for something as simple as alternating calls to Character.toLowerCase(char) and Character.toUpperCase(char) on the result of modulo (remainder of division) 2.
String x = jTextField1.getText();
for (int i = 0, len = x.length(); i < len; i++) {
char ch = x.charAt(i);
if (i % 2 == 0) {
System.out.print(Character.toLowerCase(ch));
} else {
System.out.print(Character.toUpperCase(ch));
}
}
System.out.println();
Strings start at index 0 and finish at index x.length()-1
To look up a String by index you can use String.charAt(i)
To convert a character to upper case you can do Character.toUpperCase(ch);
I suggest you build a StringBuilder from these characters which you can toString() when you are done.
you can make it using the 65 distnace of lower case and upper case ABCabc from the unicode table like:
String str = "abbfFDdshFSDjdFDSsfsSdoi".toLowerCase();
char c;
boolean state = false;
String newStr = "";
for (int i=0; i<str.length(); i++){
c = str.charAt(o);
if (state){
newStr += c;
}
else {
newStr += c + 65;
}
state = !state;
}
I'm sure there is a slicker way to do this, but this will work for a 2 minute-answer:
public String homeWork(){
String x = "Hello World";
StringBuilder sb = new StringBuilder();
for(int i=0;i<=x.length();i++){
char c = x.charAt(i);
if(i%2==0){
sb.append(String.valueOf(c).toUpperCase());
} else {
sb.append(String.valueOf(c).toLowerCase());
}
}
return sb.toString();
}
To explain i%2==0, if the remainder of i divided by 2 is equal to zero (even numbered) return true
public class PrintingStringInAlternativeCase {
public static void main(String s[])
{
String testString = "TESTSTRING";
String output = "";
for (int i = 0; i < testString.length(); i++) {
if(i%2 == 0)
{
output += Character.toUpperCase(testString.toCharArray()[i]);
}else
{
output += Character.toLowerCase(testString.toCharArray()[i]);
}
}
System.out.println("Newly generated string is as follow: "+ output);
}
}
Using as much of your code as I could, here's what I got. First I made a string called build that will help you build your resulting string. Also, I changed the index to go from [0,size-1] not [1,size]. Using modulo devision of 2 helps with the "every other" bit.
String build =""
String x=jTextField1.getText();
x=x.toLowerCase();
int y=x.length();
for(int i=0;i<y;i++)
{
if(i%2==0){
build+=Character.toUpperCase(x.charAt(i));
else{
build+=x.charAt(i);
}
}
x=build; //not necessary, you could just use build.
Happy oding! Leave a comment if you have any questions.
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Stirng");
String str=sc.nextLine();
for(int i=0;i<str.length();i++)
{
if(i%2==0)
{
System.out.print(Character.toLowerCase(str.charAt(i)));
}
else
{
System.out.print(Character.toUpperCase(str.charAt(i)));
}
}
sc.close();
}
Java 8 Solution:
static String getMixedCase(String str) {
char[] chars = str.toCharArray();
return IntStream.range(0, str.length())
.mapToObj(i -> String.valueOf(i % 2 == 1 ? chars[i] : Character.toUpperCase(chars[i])))
.collect(Collectors.joining());
}
public class ClassC {
public static void main(String[] args) {
String str = "Hello";
StringBuffer strNew = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
if (i % 2 == 0) {
strNew.append(Character.toLowerCase(str.charAt(i)));
} else {
strNew.append(Character.toUpperCase(str.charAt(i)));
}
}
System.out.println(strNew);
}
}
How can I find a repeated pattern in a string? For example, if the input file were
AAAAAAAAA
ABABAB
ABCAB
ABAb
it would output:
A
AB
ABCAB
ABAb
If you use regex, you only need one line:
String repeated = str.replaceAll("(.+?)\\1+", "$1");
Breaking down the regex (.+?)\1:
(.+?) means "at least one character, but as few as possible, captured as group 1"
\1 means "the same character(s) as group 1
Here's some test code:
String[] strs = {"AAAAAAAAA", "ABABAB", "ABCAB", "ABAb"};
for (String str : strs) {
String repeated = str.replaceAll("(.+?)\\1+", "$1");
System.out.println(repeated);
}
Output:
A
AB
ABCAB
ABAb
This outputs what you ask for - the regex can probably be improved to avoid the loop but I can't manage to fix it...
public static void main(String[] args) {
List<String> inputs = Arrays.asList("AAAAAAAAA", "ABABAB", "ABCAB", "ABAb");
for (String s : inputs) System.out.println(findPattern(s));
}
private static String findPattern(String s) {
String output = s;
String temp;
while (true) {
temp = output.replaceAll("(.+)\\1", "$1");
if (temp.equals(output)) break;
output = temp;
}
return output;
}
Written in C#, but translation should be trivial.
public static string FindPattern(string s)
{
for (int length = 1; length <= s.Length / 2; length++)
{
string pattern = s.Substring(0, length);
if(MatchesPattern(s, pattern))
{
return pattern;
}
}
return s;
}
public static bool MatchesPattern(string s, string pattern)
{
for (int i = 0; i < s.Length; i++)
{
if(!s[i].Equals(pattern[i%pattern.Length]))
{
return false;
}
}
return true;
}
If you might have spaces between the repeated segment:
(.+?)(\\ ?\\1)+
Yon don't need reexp to find pattern. Knuth-Morris-Pratt KMP Algorithm can do this much faster.
func getPattern(s string) string {
res := make([]int, len(s)+1)
i := 0
j := -1
res[0] = -1
var patternLength int
for i < len(s) {
if j == -1 || s[i] == s[j] {
i++
j++
res[i] = j
if res[i] == 0 {
patternLength++
} else {
break
}
} else {
j = res[j]
}
}
if patternLength == len(s) {
patternLength = 0
}
return s[:patternLength]
}
Unit Tests
func Test_getPattern(t *testing.T) {
testCases := []struct {
str1 string
expected string
}{
{"AAAAAAAAA", "A"},
{"ABCABC", "ABC"},
{"ABABAB", "AB"},
{"LEET", ""},
}
for _, tc := range testCases {
actual := getPattern(tc.str1)
if tc.expected != actual {
t.Errorf("Source: s1:%s\n Expected:%s\n Actual: %s",
tc.str1,
tc.expected,
actual)
}
}
}
I am trying to search an array for a couple of specific strings that I get from words in a sentence. Eventually this sentence will be in-putted by the user but I have hard coded it in at the moment to make testing easier.If the program finds the strings it should return with "Yes" and "No" if it doesn't. The problem is that I am getting yes all the Time.
public class main {
public static void main(String[]args)
{
String Sentence = "This is a sentence";
String[] CensorList =
{"big","head"};
String[] words = Sentence.split(" ");
System.out.println(words.length);
boolean match = false;
for(int i = 0; i < words.length; i++)
{
for (int j = 0; j < CensorList.length; j++)
{
if(words[i].equals(CensorList[j]))
{
match = true;
}else{
match = false;
}
}
}
if (match = true){
System.out.println("Yes");}
else{
System.out.println("No");
}
}
}
I would really appreciate any help with this one, Thanks in advance.
the if in your second for() has wrong braces.
try this one:
for (int j = 0; j < CensorList.length; j++)
{
if(words[i].equals (CensorList[j])) {
match = true;
System.out.println("Yes");
} else {
System.out.println("No");
}
match = false;
}
for your second try:
the
if (match = true)
does not compare match with true, it sets the match flag to true, which results always in true.
compare the flag in your if:
if (match == true) // or simply if (match)
{ ....
Try it:
for(int i = 0; i < words.length; i++)
{
for (int j = 0; j < CensorList.length; j++)
{
if(words[i].equals (CensorList[j]))
match = true;
}
if (match) {
System.out.println("Yes"); }
else {
System.out.println("No"); }
match = false;
}
I think you have some typos in here.
for (int j = 0; j < CensorList.length; j++)
{
if(words[i].equals (CensorList[j]));
}
This will do essentially nothing, as the if has nothing to do if the expression is evaluated to true. Then after the loop you set match to true, so it will be true always, and it will always print "Yes"
You can use a simple RegEx based solution for this
private static boolean test(String value) {
String[] CensorList = { "This", "No" };
for (String string : CensorList) {
Pattern pattern = Pattern.compile("\\b" + string + "\\b", Pattern.CASE_INSENSITIVE);
if (pattern.matcher(value).find()) {
return true;
}
}
return false;
}
Then
String string = "This is a sentence";
if(test(string)){
System.out.println("Censored");
}
Any reason you are not using String.indexOf(String) ?
Another issue is if you are doing this repeatedly for the same (very large) stirng in which case, you might want to look into more sophisticated algorithms like suffix trees or even use specialized software like Apache Lucene
Try to use
public class main {
public static void main(String[]args)
{
String Sentence = "This is a sentence";
String[] CensorList =
{"This","No"};
String[] words = Sentence.split(" ");
System.out.println(words.length);
boolean match = false;
for(int i = 0; i < words.length; i++)
{
for (int j = 0; j < CensorList.length; j++)
{
if(words[i].compareTo(CensorList[j])==0)
{
System.out.println("Yes");
}
else{System.out.println("No");}
}
}
}
I have a text (String) an I need to get only digits from it, i mean if i have the text:
"I'm 53.2 km away", i want to get the "53.2" (not 532 or 53 or 2)
I tried the solution in Extract digits from a string in Java. it returns me "532".
Anyone have an idea for it?
Thanx
You can directly use a Scanner which has a nextDouble() and hasNextDouble() methods as below:
Scanner st = new Scanner("I'm 53.2 km away");
while (!st.hasNextDouble())
{
st.next();
}
double value = st.nextDouble();
System.out.println(value);
Output: 53.2
Here is good regex site with tester:
http://gskinner.com/RegExr/
this works fine \d+\.?\d+
import java.util.regex.*;
class ExtractNumber
{
public static void main(String[] args)
{
String str = "I'm 53.2 km away";
String[] s = str.split(" ");
Pattern p = Pattern.compile("(\\d)+\\.(\\d)+");
double d;
for(int i = 0; i< s.length; i++)
{
Matcher m = p.matcher(s[i]);
if(m.find())
d = Double.parseDouble(m.group());
}
System.out.println(d);
}
}
The best and simple way is to use a regex expression and the replaceAll string method. E.g
String a = "2.56 Kms";
String b = a.replaceAll("\\^[0-9]+(\\.[0-9]{1,4})?$","");
Double c = Double.valueOf(b);
System.out.println(c);
If you know for sure your numbers are "words" (space separated) and don't want to use RegExs, you can just parse them...
String myString = "I'm 53.2 km away";
List<Double> doubles = new ArrayList<Double>();
for (String s : myString.split(" ")) {
try {
doubles.add(Double.valueOf(s));
} catch (NumberFormatException e) {
}
}
I have just made a method getDoubleFromString. I think it isn't best solution but it works good!
public static double getDoubleFromString(String source) {
if (TextUtils.isEmpty(source)) {
return 0;
}
String number = "0";
int length = source.length();
boolean cutNumber = false;
for (int i = 0; i < length; i++) {
char c = source.charAt(i);
if (cutNumber) {
if (Character.isDigit(c) || c == '.' || c == ',') {
c = (c == ',' ? '.' : c);
number += c;
} else {
cutNumber = false;
break;
}
} else {
if (Character.isDigit(c)) {
cutNumber = true;
number += c;
}
}
}
return Double.parseDouble(number);
}