I got a question in vb.net
can I identify each of the character in string
for an example
i got a string of "Hello!. Good Afternoon!"
from this string can i trim away the period symbol?
Thank you
You should look at the methods of the String class, as they support different forms of string manipulation.
At its simplest, the Replace() method can be used to replace all occurrences of a period character with an empty string.
Alternatively, you can use the IndexOf() method to locate a specific string (e.g. the period) and the Remove() method to remove that character.
According to my 8-ball Magic, you actually want to :
Remove concecutive punctuation from a string:
With a Regex we are going to find all punctuation in the string.
The index of Match will be into an int[].
We will go iterate throught the array to find if the index is concecutive to the last punctuation index.
We will delete all the punctuation starting by the last one. Because starting with the 1rst will modify the index.
Code:
string Input = "....Thalassius! vero ea--*/-*/-- tempestate+- fectus";
string Output = Input;
var regex = new Regex(#"[^\w\s]|_"); // *1.
var matches = regex.Matches(Input) ;
var MatchesIndex = matches .Cast<Match>()
.Select(match => match.Index)
.ToArray(); // *2.
int last = 0;
List<int> toDelete = new List<int>();
for (int i = 0; i < MatchesIndex.Length; i++) // *3.
{
if ( MatchesIndex[i] == last + 1)
toDelete.Add(MatchesIndex[i]);
last = MatchesIndex[i];
}
foreach (int i in toDelete.OrderByDescending(x => x)) // *4.
Output = Output.Remove(i, 1);
Console.WriteLine("Input : " + Input);
Console.WriteLine("Output : " + Output);
C# Snippet
You can learn more about the regex used, thanks to #John Kugelman.
Related
How can I add a trail of six 0 of decimal places to a number in string type?
I tried PadRight but didn't get the result that I wanted. For example:
125 ===to===> 125,000000
14,5 ===to===> 14,500000
so on..
Is there any function in VB.NET can do that or do I need to split the string then combine them?
I'm not completely sure what you're asking, but if you want to add six 0's to a string then I would make a function, something like this:
private static string AddZeroes(string myString)
{
//Makes an array that is 6 elements higher than the original string
string[] myStringArray = new string[myString.Length + 6];
//Sets the array to have all elements of myString inside of it
for (int i = 0; i < myString.Length; i++)
{
myStringArray[i] = Convert.ToString(myString[i]);
}
//Adds the six 0's to the array
for (int i = myString.Length; i < myString.Length + 6; i++)
{
myStringArray[i] = "0";
}
//Sets myString to an empty string, then adds all the contents of the myStringArray to it
myString = "";
for (int i = 0; i < myStringArray.Length; i++)
{
myString += myStringArray[i];
}
//Returns the string that should now have six 0's added to the end
return myString;
}
If you wanted a comma or decimal, it shouldn't be too hard to just add one right before the for loop that adds the 0's, and also make sure that the array is the length of the string + 7 instead, to fit that extra character.
I want to obtain the index chars or words in a string
for example
tv.text=" hey how are you, are you okay"
val res=tv.text.indexOf('h')
(have any way for put string instead of char?
output res=0
index of return only first char with h but in my tv text I have more h chars
can we return all h chars indexs
You can use filter function to get all the string indices with the required character.
val text = " hey how are you, are you okay"
val charToSearch = 'h'
val occurrences = text.indices.filter { text[it] == charToSearch }
println(occurences)
Try it yourself
And, if you want to search for strings instead of a single character, you can do this:
text.indices.filter { text.startsWith(stringToSearch, it) }
The following should work (you try to find an index if you found one in the previous iteration and you begin the folloing iteration from the previously found character instance plus 1, so that you don't find the same again and again):
fun main() {
val word = " hey how are you, are you okay"
val character = 'h'
var index: Int = word.indexOf(character)
while (index >= 0) {
println(index)
index = word.indexOf(character, index + 1)
}
}
If you want to store the indexes for later usage you can also do the following:
fun main() {
val word = " hey how are you, are you okay"
val character = 'h'
val indexes = mutableListOf<Int>()
var index: Int = word.indexOf(character)
while (index >= 0) {
index = word.indexOf(character, index + 1)
indexes.add(index)
}
println(indexes)
}
If you just want all the indices matching a char you can do this:
text.indices.filter { text[it] == 'h' }
Finding string matches is trickier, you could use Kotlin's regionMatches function to check if the part of the string starting at index matches what you're looking for:
val findMe = "you"
text.indices.filter { i ->
text.regionMatches(i, findMe, 0, findMe.length)
}
You could use a regular expression too, so long as you're careful about validating the search pattern:
Regex(findMe).findAll(text)
.map { it.range.first() } // getting the first index of each matching range
.toList()
I am searching a string of DNA chars, ATCG. I may wish to look for AT for example and the search must ignore ATAT not find two AT's. I need to know how many AT,s there are in the string and their position in there position.
I tried various ideas but so far have failed. I used Mid, Contains. If someone can give me a hint I would be grateful.
Regards
Not a VB.NET dude (C# is my current dope), but luckily they're similar. If you don't care about execution time, you can just brute force it. First, see if your pattern occurs in the string at all:
bool containsAT myDNAChars.Contains( "AT" );
Then you can go about finding their positions:
var myListOfMatches = new List<int>();
int searchIndex = 0;
string pattern = "AT";
bool done = false;
while( !done )
{
int atIndex = myDNAChars.IndexOf( pattern, searchIndex );
myListOfMatches.Add( atIndex );
searchIndex += pattern.Length;
if( searchIndex > myDNAChars.Length )
{
done = true;
}
}
Once you have a list of matches, you can iterate over it and discard any occurrences of "ATAT" or any other patterns you don't want.
It's not elegant--it's brute force--but it should work.
Sorry about the C#, but it should be easy to convert to VB.NET.
I want to keep white space when I call text attribute of token, is there any way to do it?
Here is the situation:
We have the following code
IF L > 40 THEN;
ELSE
IF A = 20 THEN
PUT "HELLO";
In this case, I want to transform it into:
if (!(L>40){
if (A=20)
put "hello";
}
The rule in Antlr is that:
stmt_if_block: IF expr
THEN x=stmt
(ELSE y=stmt)?
{
if ($x.text.equalsIgnoreCase(";"))
{
WriteLn("if(!(" + $expr.text +")){");
WriteLn($stmt.text);
Writeln("}");
}
}
But the result looks like:
if(!(L>40))
{
ifA=20put"hello";
}
The reason is that the white space in $stmt was removed. I was wondering if there is anyway to keep these white space
Thank you so much
Update: If I add
SPACE: [ ] -> channel(HIDDEN);
The space will be preserved, and the result would look like below, many spaces between tokens:
IF SUBSTR(WNAME3,M-1,1) = ')' THEN M = L; ELSE M = L - 1;
This is the C# extension method I use for exactly this purpose:
public static string GetFullText(this ParserRuleContext context)
{
if (context.Start == null || context.Stop == null || context.Start.StartIndex < 0 || context.Stop.StopIndex < 0)
return context.GetText(); // Fallback
return context.Start.InputStream.GetText(Interval.Of(context.Start.StartIndex, context.Stop.StopIndex));
}
Since you're using java, you'll have to translate it, but it should be straightforward - the API is the same.
Explanation: Get the first token, get the last token, and get the text from the input stream between the first char of the first token and the last char of the last token.
#Lucas solution, but in java in case you have troubles in translating:
private String getFullText(ParserRuleContext context) {
if (context.start == null || context.stop == null || context.start.getStartIndex() < 0 || context.stop.getStopIndex() < 0)
return context.getText();
return context.start.getInputStream().getText(Interval.of(context.start.getStartIndex(), context.stop.getStopIndex()));
}
Looks like InputStream is not always updated after removeLastChild/addChild operations. This solution helped me for one grammar, but it doesn't work for another.
Works for this grammar.
Doesn't work for modern groovy grammar (for some reason inputStream.getText contains old text).
I am trying to implement function name replacement like this:
enterPostfixExpression(ctx: PostfixExpressionContext) {
// Get identifierContext from ctx
...
const token = CommonTokenFactory.DEFAULT.createSimple(GroovyParser.Identifier, 'someNewFnName');
const node = new TerminalNode(token);
identifierContext.removeLastChild();
identifierContext.addChild(node);
UPD: I used visitor pattern for the first implementation
I am coding VB.NET in VS2008.
I have a comma delimited string of numbers, i.e. 16,7,99,1456,1,3
I do this in VB:
Dim MyArr() As String = MyString.Split(",")
Will MyArr keep the items in the order they were in the string?
If I do this:
For Each S as String in MyString.Split(",")
'Do something with S
'Will my items be in the same order they were
'in the string?
Next
I tested it and it appears to keep the sort order but will it ~always~ keep the order?
If it does not maintain the order then what is a good way to split a string and keep order?
I'm asking because MSDN Array documentation says: "The Array is not guaranteed to be sorted." So I'm a bit unsure.
Yes, in your example the items will stay in the original order.
The MSDN documentation indicates that an Array is not necessarily sorted just because it's an Array, but once the items are in the Array, they won't be rearranged. The Split() operation will break it down based on the given token, preserving the order.
Yes, order will be maintained for these operations.
Yes, String.Split walks down the string, everything will stay in order. From .NET Reflector:
private string[] InternalSplitKeepEmptyEntries(int[] sepList, int[] lengthList, int numReplaces, int count)
{
int startIndex = 0;
int index = 0;
count--;
int num3 = (numReplaces < count) ? numReplaces : count;
string[] strArray = new string[num3 + 1];
for (int i = 0; (i < num3) && (startIndex < this.Length); i++)
{
strArray[index++] = this.Substring(startIndex, sepList[i] - startIndex);
startIndex = sepList[i] + ((lengthList == null) ? 1 : lengthList[i]);
}
if ((startIndex < this.Length) && (num3 >= 0))
{
strArray[index] = this.Substring(startIndex);
return strArray;
}
if (index == num3)
{
strArray[index] = Empty;
}
return strArray;
}
In .NET strings are immutable objects. Long story short, the string S and those returned by Split(",") live in different memory.