How to check if a String contains two same characters? - string

In my case a string contains for example something like 2500.00. Also you input a string in the same format for example 250.0 which would be converted to 250.00. These strings will be converted to float and they will be added or subtracted.
Now I want to check if the string contains two "." somewhere for example 2.50.00 or 250..00. In that case an errormessage should be displayed.
Therefore my question is how am I able to check if a string contains two "." characters at any position of the string?

You may check if a dot appears more than once in a string with a simple method checking if the first index of the char is not equal to the index of the last char occurrence:
boolean containsTwoDots(String str) {
return str.indexOf('.') != str.lastIndexOf('.');
}

Related

Apex - remove special characters from a string except for ''+"

In Apex, I want to remove all the special characters in a string except for "+". This string is actually a phone number. I have done the following.
String sampleText = '+44 597/58-31-30';
sampleText = sampleText.replaceAll('\\D','');
System.debug(sampleText);
So, what it prints is 44597583130.
But I want to keep the sign + as it is represents 00.
Can someone help me with this ?
Possible solutions
String sampleText = '+44 597/58-31-30';
// exclude all characters which you want to keep
System.debug(sampleText.replaceAll('[^\\+|\\d]',''));
// list explicitly each char which must be replaced
System.debug(sampleText.replaceAll('/|-| ',''));
Output in both case will be the same
|DEBUG| +44597583130
|DEBUG| +44597583130
Edit
String sampleText = '+0032 +497/+59-31-40';
System.debug(sampleText.replaceAll('(?!^\\+)[^\\d]',''));
|DEBUG|+0032497593140

Specman string: How to split a string to a list of its chars?

I need to split a uint to a list of bits (list of chars, where every char is "0" or "1", is also Ok). The way I try to do it is to concatenate the uint into string first, using binary representation for numeric types - bin(), and then to split it using str_split_all():
var num : uint(bits:4) = 0xF; // Can be any number
print str_split_all(bin(num), "/w");
("/w" is string match pattern that means any char).
The output I expect:
"0"
"b"
"1"
"1"
"1"
"1"
But the actual output is:
0. "0b1111"
Why doesn't it work? Thank you for your help.
If you want to split an integer into a list of bits, you can use the %{...} operator:
var num_bits : list of bit = %{num};
You can find a working example on EDAPlayground.
As an extra clarification to your question, "/w" doesn't mean match any character. The string "/\w/" means match any single character in AWK Syntax. If you put that into your match expression, you'll get (almost) the output you want, but with some extra blanks interleaved (the separators).
Regardless, if you want to split a string into its constituting characters, str_split_all(...) isn't the way to go. It's easier to convert the string into ASCII characters and then convert those back to string again:
extend sys {
run() is also {
var num : uint(bits:4) = 0xF; // Can be any number
var num_bin : string = bin(num);
var num_bin_chars := num_bin.as_a(list of byte);
for each (char) in num_bin_chars {
var char_as_string : string;
unpack(packing.low, %{8'b0, char}, char_as_string);
print char_as_string;
};
};
};
The unpack(...) syntax is directly from the e Reference Manual, Section 2.8.3 Type Conversion Between Strings and Scalars or Lists of Scalars

How to check if there's only numbers in string

how to check if there is only numbers in the string?
I want to skip some code with goto if there's only numbers in the string.
Thanks
try
i := StrToInt( str );
except
{ str is NOT an integer }
end;
A simple google: Pascal Help
StrToInt
Convert a string to an integer value.
Declaration
Source position: sysstrh.inc line 113
function StrToInt( const s: string ):Integer; Description
StrToInt will convert the string Sto an integer. If the string
contains invalid characters or has an invalid format, then an
EConvertError is raised.
To be successfully converted, a string can contain a combination of
numerical characters, possibly preceded by a minus sign (-). Spaces
are not allowed.
The string S can contain a number in decimal, hexadecimal, binary or
octal format, as described in the language reference. For enumerated
values, the string must be the name of the enumerated value. The name
is searched case insensitively.
For hexadecimal values, the prefix '0x' or 'x' (case insensitive) may
be used as

How to extract substring in Groovy?

I have a Groovy method that currently works but is real ugly/hacky looking:
def parseId(String str) {
System.out.println("str: " + str)
int index = href.indexOf("repositoryId")
System.out.println("index: " + index)
int repoIndex = index + 13
System.out.println("repoIndex" + repoIndex)
String repoId = href.substring(repoIndex)
System.out.println("repoId is: " + repoId)
}
When this runs, you might get output like:
str: wsodk3oke30d30kdl4kof94j93jr94f3kd03k043k?planKey=si23j383&repositoryId=31850514
index: 59
repoIndex: 72
repoId is: 31850514
As you can see, I'm simply interested in obtaining the repositoryId value (everything after the = operator) out of the String. Is there a more efficient/Groovier way of doing this or this the only way?
There are a lot of ways to achieve what you want. I'll suggest a simple one using split:
sub = { it.split("repositoryId=")[1] }
str='wsodk3oke30d30kdl4kof94j93jr94f3kd03k043k?planKey=si23j383&repositoryId=31850514'
assert sub(str) == '31850514'
Using a regular expression you could do
def repositoryId = (str =~ "repositoryId=(.*)")[0][1]
The =~ is a regex matcher
or a shortcut regexp - if you are looking only for single match:
String repoId = str.replaceFirst( /.*&repositoryId=(\w+).*/, '$1' )
All the answers here contains regular expressions, however there are a bunch of string methods in Groovy.
String Function
Sample
Description
contains
myStringVar.contains(substring)
Returns true if and only if this string contains the specified sequence of char values
equals
myStringVar.equals(substring)
This is similar to the above but has to be an exact match for the check to return a true value
endsWith
myStringVar.endsWith(suffix)
This method checks the new value contains an ending string
startsWith
myStringVar.startsWith(prefix)
This method checks the new value contains an starting string
equalsIgnoreCase
myStringVar.equalsIgnoreCase(substring)
The same as equals but without case sensitivity
isEmpty
myStringVar.isEmpty()
Checks if myStringVar is populated or not.
matches
myStringVar.matches(substring)
This is the same as equals with the slight difference being that matches takes a regular string as a parameter unlike equals which takes another String object
replace
myStringVar.replace(old,new)
Returns a string resulting from replacing all occurrences of oldChar in this string with newChar
replaceAll
myStringVar.replaceAll(old_regex,new)
Replaces each substring of this string that matches the given regular expression with the given replacement
split
myStringVar.split(regex)
Splits this string around matches of the given regular expression
Source

Best way to compare multiple string in java

Suppose I have a string "That question is on the minds of every one.".
I want to compare each word in string with a set of word I.e. (to , is ,on , of) and if those word occurs I want to append some string on the existing string.
Eg.
to = append "Hi";
Is = append "Hello";
And so on.
To be more specific I have used StringTokenizer to get the each word and compared thru if else statement. However we can use Switch also but it is available in Jdk 1.
7.
I don't know if this is what you mean, but:
You could use String.split() to separate the words from your string like
String[] words = myString.split(" ");
and then, for each word, compare it with the given set
for(String s : words)
{
switch(s)
{
case("to"):
[...]
}
}
Or you could just use the String.contains() method without even splitting your string, but I don't know if that's what you wanted.
Use a HashMap<String,String> variable to store your set of words and the replacement words you want. Then split your string with split(), loop through the resulting String[] and for each String in the String[], check whether the HashMap containsKey() that String. Build your output/resulting String in the loop - if the word is contained in the HashMap, replace it with the value of the corresponding key in the HashMap, otherwise use the String you are currently on from the String[].

Resources