How to substring based on a specific characters through iteration? - iteration

I have this following string
String oldStr = ".abc.def.ghi.klm.";
How do I retrieve the substring and put into another string using a loop?
for (int i = 0; i < oldStr.length(); ++i) {
String newStr = doSomethingMethod("oldStr");
}
where oldStr should be "abc", "def", "ghi", "klm" recursively
I tried to use StringUtils.subStringBetween(oldStr, ".", ".") but that only handle the first substring. Any help is greatly appreciated.

I am not sure what results your looking for but i would just use the Split method with the period and get a string array. now each element is a new string.
var results = oldstring.Split('.');
this gives you an array... "abc", "def", "ghi" ...
if you simply want to remove the periods then you can just use the Replace method
var newstring = oldstring.Replace(".","");
now you have a string "abcdefghjklm"

Related

Using List inside a postgres Query

i have a dynamic list.
list=['a','b','c','d' ..... ] so length may change
i want to compare these list values in a query
select * from student where name in(all the list values);
i want to pass list values into this query
how i can do this.. ??? please help
Thank you
In Postgres, you can use arrays. The syntax in the where clause looks like:
where name = any (array[1, 2, 3])
or
where name = any (list_parameter)
You can write a function that gets a list as a parameter and return a string like "'one', 'two','three'".
// need a string like this 'one', 'two'
private String arrayToSqlInChecker(List<String> loc_list) {
StringBuilder value = new StringBuilder("");
for (int i = 0; i < loc_list.size(); i++) {
value.append("'" + loc_list.get(i) + "'");
if (i != loc_list.size() - 1) {
value.append(",");
}
}
return value.toString();
}
And then you have to append this string into you PostgreSQL IN query
"id IN (" + this.arrayToSqlInChecker(loc_list) + ")"
You can also handle null or empty values in the function

convert listbox value to comma separated string with single quotes

i have a listbox with more than 100 items i want this 100 items to be comma separated with single quotes e.g: ''abc','def'' i want this to search in a select clause
List<string> SelectedValue = new List<string>();
foreach (ListItem lst in ListBox2.Items)
{
if (lst.Selected)
{
SelectedValue.Add(lst.Value);
}
}
string.Join(",",SelectedValue.Select(x=>string.Format("'{0}'",x)));
its giving me error 'the best overloaded method match for 'string.join has some invalid arguments, what an doing wrong here
Might I suggest a slightly different approach using a StringBuilder instead of putting the items into a List object? You are flatting these out to CSV anyways, so why not just build it that way like so..
var SB = new StringBuilder();
foreach (ListItem lst in ListBox2.Items)
{
if (lst.Selected)
{
SB.Append("'" + list.value + "',");
}
}
var FinalString = SB.ToString().Substring(0, (SB.Length - 1));
You linq query returns a result of type IEnumerable you must convert it to a string array:
List<string> selectedValue = (from ListItem lst in ListBox1.Items
where lst.Selected
select lst.Value).ToList();
//convert to array using ToArray()
string[] arr = selectedValue.Select(x => string.Format("'{0}'", x)).ToArray();
string data = string.Join(",",arr);
You need to convert the result of SelectedValue.Select to an array:
String result = string.Join(",", SelectedValue.Select(x => string.Format("'{0}'", x)).ToArray());`

hibernate how to assign ParameterList for the IN clause

I need to use the IN clause in the SQL sentence.
I have data in one table with the type on Int(11).
And Y have a String from another table that is the criteria.
For example, in table A i have the value 3 of type Int.
In table/process B i have the String "0123".
I need to query table A to meet this criteria:
Select * from Table A where attrib_1 IN (0,1,2,3)
Because record n have value 3, it should be returned.
So i'm trying to use .setParameterList, like this:
List<BloqueCruzamiento> bloques = session.createQuery("FROM BloqueCruzamiento AS b WHERE b.anio=:anio AND b.activo=true AND b.grupo=:categoria AND b.pr IN(:pr_set)ORDER BY b.nroParcela, b.cruza, b.pedigree")
.setParameter("anio", grupo.getAnio())
.setParameter("categoria", grupo.getCategoria())
.setParameterList("pr_set", pr_parm)
.list();
the quid is on "pr_set" parameter.
I want to know how to convert a String , "0123", to a Collection of Integers (0,1,2,3).
So I can pass this parameter to setParameterList() method.
Anapproach that I'm right now is to convert the String to a Char Array, then loop, and convert each element into an Integer Array.
Can somebody give anothe solution ?
Regards
you can use code below to get list from String
String s = "0123";
List<Integer> pr_parm = new ArrayList<Integer>();
for(int i=0;i<s.length();i++) {
if (Character.isDigit(s.charAt(i))) {
pr_parm.add(Integer.parseInt(String.valueOf(s.charAt(i))));
}
}
System.out.println(pr_parm);
Then you can use the list in your setParameterList("pr_set", pr_parm)
this was the solution.
String[] sele = grupo.getPr_sel().split(",");
Integer[] pr_parm_int = new Integer[sele.length];
for (int x=0; x<sele.length;x++){
pr_parm_int[x] = Integer.valueOf(sele[x]);
}
the first line is to parse the string and strip comas.

Is there a built-in function to extract all characters in a string up until the first occurrence of a space?

Is there a built-in function to extract all characters in a string up until the first occurrence of a space?
Say the string is:
Methicillin-resistant staphylococcus aureus
I want to be able to get the substring:
Methicillin-resistant
You can do it in two functions:
newstring = mystring.Substring(0, mystring.IndexOf(" "))
Although that will fail if there's no space in mystring.
So you could pull out mystring.IndexOf(" ") into a variable and check whether it's -1 (no space found) before you try to use it in Substring.
The first solution you can use is a simple IndexOf
string GetFirstWord(string source)
{
int index = source.IndexOf(" ");
if (index == -1) return source;
else return source.Substring(0, index);
}
The second solution can be used if you want to keep all words into a string array.
string[] GetWords(string source)
{
return source.Split(' ');
}
if you only want the first word, you can use it like this :
string word = GetWords("Methicillin-resistant staphylococcus aureus")[0];
And a VB.NET solution. No, it can't be done with one built-in method; you need two:
Left(myString, InStr(myString, " ") - 1)
And like the other solutions you need to check InStr doesn't return 0 if myString may not contain a space.

How to filter out some vulnerability causing characters in query string?

I need to filter out characters like /?-^%{}[];$=*`#|&#'\"<>()+,\. I need replace this with empty string if it is there in the query string. Please help me out. I am using this in ASP pages.
Best idea would be to use a function something along the lines of:
Public Function MakeSQLSafe(ByVal sql As String) As String
'first i'd avoid putting quote chars in as they might be valid? just double them up.
Dim strIllegalChars As String = "/?-^%{}[];$=*`#|&#\<>()+,\"
'replace single quotes with double so they don't cause escape character
If sql.Contains("'") Then
sql = sql.Replace("'", "''")
End If
'need to double up double quotes from what I remember to get them through
If sql.Contains("""") Then
sql = sql.Replace("""", """""")
End If
'remove illegal chars
For Each c As Char In strIllegalChars
If sql.Contains(c.ToString) Then
sql = sql.Replace(c.ToString, "")
End If
Next
Return sql
End Function
This hasn't been tested and it could probably be made more efficient, but it should get you going. Wherever you execute your sql in your app, just wrap the sql in this function to clean the string before execution:
ExecuteSQL(MakeSQLSafe(strSQL))
Hope that helps
As with any string sanitisation, you're much better off working with a whitelist that dictates which characters are allowed, rather than a blacklist of characters that aren't.
This question about filtering HTML tags resulted in an accepted answer suggesting the use of a regular expression to match against a whitelist: How do I filter all HTML tags except a certain whitelist? - I suggest you do something very similar.
I'm using URL Routing and I found this works well, pass each part of your URL to this function. It's more than you need as it converts characters like "&" to "and", but you can modify it to suit:
public static string CleanUrl(this string urlpart) {
// convert accented characters to regular ones
string cleaned = urlpart.Trim().anglicized();
// do some pretty conversions
cleaned = Regex.Replace(cleaned, " ", "-");
cleaned = Regex.Replace(cleaned, "#", "no.");
cleaned = Regex.Replace(cleaned, "&", "and");
cleaned = Regex.Replace(cleaned, "%", "percent");
cleaned = Regex.Replace(cleaned, "#", "at");
// strip all illegal characters like punctuation
cleaned = Regex.Replace(cleaned, "[^A-Za-z0-9- ]", "");
// convert spaces to dashes
cleaned = Regex.Replace(cleaned, " +", "-");
// If we're left with nothing after everything is stripped and cleaned
if (cleaned.Length == 0)
cleaned = "no-description";
// return lowercased string
return cleaned.ToLower();
}
// Convert accented characters to standardized ones
private static string anglicized(this string urlpart) {
string beforeConversion = "àÀâÂäÄáÁéÉèÈêÊëËìÌîÎïÏòÒôÔöÖùÙûÛüÜçÇ’ñ";
string afterConversion = "aAaAaAaAeEeEeEeEiIiIiIoOoOoOuUuUuUcC'n";
string cleaned = urlpart;
for (int i = 0; i < beforeConversion.Length; i++) {
cleaned = Regex.Replace(urlpart, afterConversion[i].ToString(), afterConversion[i].ToString());
}
return cleaned;
// Spanish : ÁÉÍÑÓÚÜ¡¿áéíñóúü"
}