for (int i = 0; i < links.Count; i++)
{
int f = links[i].IndexOf("http");
}
links is List<string>
For example in index 0 I have: http://test/107281.shtml#34
I want to extract from this link only this:
http://test/107281.shtml without the #34 in the end.
But for the start why f return 0 all the time ?
It's right...., cause this string "http" start index is 0, if couldn't found string, IndexOf will return -1...
The first char in a string is located at index 0, so in the string http://test/107281.shtml#34 as http is the first thing in the string its located at index 0...
To extract you can use either regex or indexOf("#") in combination with substring.
The indexOf() method returns the position of the first occurrence of a specified value in a string.
var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");
Output wil be : 13
which is the position number.
Next you remove from which position you want to delete.
I guess you are looking for something like:
for (int i = 0; i < links.Count; i++)
{
int f = links[i].IndexOf("#");
}
This should give you the index of the first #.
IndexOf("http") should give you 0 as http is at index 0.
To get the string you are seeking:
for (int i = 0; i < links.Count; i++)
{
var url = links[i].Substring(0, links[i].IndexOf("#"));
}
Example using your demo string HERE.
List<string> link_list = new List<string> { "http://test/107281.shtml#34", "http://test/107281.shtml#35" };
List<string> new_list = new List<string>();
foreach (var item in link_list)
{
string bb = item.Substring(0, item.ToString().IndexOf("#"));
new_list.Add(bb);
}
Related
I want to make a program that finds how many times a key word has been repeated (i.e. "the") and then store the index position in a array. At the moment, my code only store's the first time it reads "the" in the string sentence. How do you make it that it stores the index position of the first time it reads "the" and the second?
It outputs on the console:
11
0
My current code:
string sentence = "John likes the snow and the winter.";
string keyWord = "the";
var test = sentence.Split(new char[] { ' ', '.' });
var count = Array.FindAll(test, s => s.Equals(keyWord.Trim())).Length;
int[] arr = new int[count];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = sentence.IndexOf("the", i);
i++;
}
foreach (int num in arr)
{
Console.WriteLine(num);
}
Console.ReadLine();
Second result (0) is there because of unnecessary i++ in the for loop. Because of that, you are entering the loop only once. To achieve what you want you could try code like below (please take a closer look at body of the for loop:
string sentence = "John likes the snow and the winter.";
string keyWord = "the";
var test = sentence.Split(new char[] { ' ', '.' });
var count = Array.FindAll(test, s => s.Equals(keyWord.Trim())).Length;
int[] arr = new int[count];
int lastIndex = 0;
for (int i = 0; i < arr.Length; i++)
{
lastIndex = sentence.IndexOf("the", lastIndex + keyWord.Length); //We are adding length of the `keyWord`, because we want to skip word we already found.
arr[i] = lastIndex;
}
foreach (int num in arr)
{
Console.WriteLine(num);
}
Console.ReadLine();
I hope it makes sense.
There are two problems that I see with your code. First, you're incrementing i twice, so it will only ever get half the items. Second, you're passing i as the second parameter to IndexOf (which represents the starting index for the search). Instead, you should be starting the search after the previous found instance by passing in the index of the last instance found plus its length.
Here's a fixed example of the for loop:
for (int i = 0; i < arr.Length; i++)
{
arr[i] = sentence.IndexOf(keyword, i == 0 ? 0 : arr[i - 1] + keyword.Length);
}
Also, your code could be simplified a little if you use a List<int> instead of an int[] to store the indexes, because with List you don't need to know the count ahead of time:
string sentence = "John likes the snow and the winter.";
string keyWord = "the";
var indexes = new List<int>();
var index = 0;
while (true)
{
index = sentence.IndexOf(keyWord, index); // Find the next index of the keyword
if (index < 0) break; // If we didn't find it, exit the loop
indexes.Add(index++); // Otherwise, add the index to our list
}
foreach (int num in indexes)
{
Console.WriteLine(num);
}
The parameter is a string that has a number in each word. I need to search that word for the number. My solution so far is to split the string up into a string array, and use Array.IndexOf to find the matching index of my search. However I haven't been able to find a way to successfully use wildcards. Using string.Contains seems to work, but searching with Array.IndexOf doesn't.
How can I search a string array element for a word that contains a number and return it's index? 1-9.
public static string Order(string words)
{
string[] wordArr = words.Split(' ');
string[] wordsOrdered = new string[words.Length];
int k;
for (int i = 0, j = 1; i < wordsOrdered.Length; i++, j++)
{
if (words.Contains($"{j}"))
{
k = Array.IndexOf(wordArr, $"{j}");
if (k != -1)
wordsOrdered[i] = wordArr[k];
}
}
return words = wordsOrdered.ToString();
}
A Regular Expression that looks for the presence of digits in your words seems the most simple solution
public static string Order(string words)
{
string[] wordArr = words.Split(' ');
string[] wordsOrdered = new string[wordArr.Length];
Regex r = new Regex(#"\d+");
for (int i = 0; i < wordArr.Length; i++)
{
var m = r.Match(wordArr[i]);
if(m.Success)
{
int index = Convert.ToInt32(m.Value);
wordsOrdered[index-1] = wordArr[i];
}
}
return string.Join(" ", wordsOrdered);
}
This code assumes that all your words have at least one number internally and the lowest number start at 1. (A 0 will result in an index out of range exception) and also you shouldn't have numbers that are greater than then count of the input words.
I'm trying to cycle through chars in a string.
string cycleMe = "Hi StackOverflow! Here is my string."
However, I want to skip over certain ranges of indexes. The ranges I want to skip over are stored in a List of objects, delims.
List<Delim> delims = delimCreator();
To retrieve each starting index and ending index for a range, I have to write a loop that accesses each "delim":
delims[0].getFirstIndex() //results in, say, index 2
delims[0].getLastIndex() //results in, say, index 4
delims[1].getFirstIndex() //results in, say, index 5
delims[1].getLastIndex() //results in, say, index 7
(there can be infinitely many "delim" objects in play)
If the above were my list, I'd want to print the string cycleMe, but skip all the chars between 2 and 4 (inclusive) and 5 and 7 (inclusive).
Expected output using the numbers above:
HiOverflow! Here is my string.
Here is the code I have written so far. It loops far more often than I'd expect (it loops ~x2 the number of characters in the string). Thanks in advance! =)
List<Delim> delims = delimAggregateInator(displayTextRaw);
for (int x = 0; x < cycleMe.Length;x++){
for (int i = 0; i < delims.Count; i++){
if (!(x >= delims[i].getFirstIndex() && x <= delims[i].getLastIndex())){
Debug.Log("test");
}
}
I assume that by skipping you meant you want to omit those characters from the original string. If that is the case, you can try Aggregate extension method like below.
string result = delims.Aggregate<Delim, string>(cycleMe, (str, d) => cycleMe = cycleMe.Remove(d.FirstIndex, (d.LastIndex - d.FirstIndex) + 1));
Make sure that the delim list is in the proper order.
Solution might be converting the string to char array, replacing the desired parts to spaces, and converting the output back to string.
Here is the modified version of your code:
string cycleMe = "Hi StackOverflow! Here is my string."
var charArray = cycleMe.ToCharArray(); // Converting to char array
List<Delim> delims = delimAggregateInator(displayTextRaw);
for (int x = 0; x < cycleMe.Length;x++){
for (int i = 0; i < delims.Count; i++){
// ORIGINAL: if (!(x >= delims[i].getFirstIndex() && x <= delims[i].getLastIndex())){
if (x >= delims[i].getFirstIndex() && x <= delims[i].getLastIndex()){
Debug.Log("test");
charArray[x] = ' '; // Replacing the item with space
}
}
string output = new string(charArray); // Converting back to string
P.S. This is probably not the most optimal solution but at least it should work.
You should use LINQ for that
struct Delim
{
public int First { get; set; }
public int Last { get; set; }
}
static void Main(string[] args)
{
string cycleMe = "Hi StackOverflow! Here is my string.";
var delimns = new List<Delim> { new Delim { First=2, Last=4}, new Delim { First = 5, Last = 7 } };
var cut = cycleMe.Where((c, i) =>
!delimns.Any(d => i >= d.First && i <= d.Last));
Console.WriteLine(new string(cut.ToArray());
}
That means I am basically only selecting letters, at positions which are not part of any cutting range.
Also: Fix your naming. A delimiter is a character, not a position (numeric)
Imagine i have 2 lists filled with values. I want all the elements from the first list, written into the first column, all the elements from the second list written into the second column and so on.
If both list have the same size, this works fine:
for (int i = 0; i < valueArray.Count(); i++)
{
var newLine = string.Format("{0},{1}", valueArray.ElementAt(i), secondValueArray.ElementAt(i));
sw.Write(newLine);
}
My problem is that if the lists have different sizes, code fails with out of range exception obviously. I tried adding ',' between columns but it's not working.
Instead of ElementAt you should use ElementAtOrDefault :
According to msdn it
Returns the element at a specified index in a sequence or a default
value if the index is out of range.
try this :
List<int?> valueArray = new List<int?>();
List<int?> secondValueArray = new List<int?>();
//... fill lists
valueArray.Add( 1 );
valueArray.Add(2);
valueArray.Add(3);
secondValueArray.Add( 4 );
while (valueArray.Count > secondValueArray.Count)
secondValueArray.Add(null);
while (secondValueArray.Count > valueArray.Count)
valueArray.Add(null);
for (int i = 0; i < valueArray.Count(); i++)
{
var newLine = string.Format("{0},{1}", valueArray.ElementAt(i), secondValueArray.ElementAt(i));
Console.WriteLine(newLine);
}
;
Result :
1,4
2,
3,
As mentioned before, use ElementAtOrDefault(). And check which array is the longest one. Furthermore, you might want to write an empty string instead of NULL if there's no value.
int count = Math.Max(firstArray.Count(), secondArray.Count());
for (int i = 0; i < count; i++)
{
var value1 = firstArray.ElementAtOrDefault(i) ?? String.Empty;
var value2 = secondArray.ElementAtOrDefault(i) ?? String.Empty;
var newLine = string.Format("{0},{1}", value1, value2);
sw.Write(newLine);
}
I have an string array of size 10:
[0] = "1,0000000"
[1] = "479,00000"
....
[9] = "145,0".
I want to remove the trailing ",00000" of the first 9 elements with regex and linq. Please help.
Basically I would do this like that :
var yourArray = new string[10];
var yourResult = yourArray.Take(9).Select(s => s.Split(',')[0]).ToArray();
But you can replace the Select method content with a Regex call if you wish.
Use a for-loop and string methods like IndexOf and Substring:
for(int i = 0; i < Math.Min(array.Length, 9); i++)
{
int commaIndex = array[i].IndexOf(",");
if(commaIndex >= 0) array[i] = array[i].Substring(0, commaIndex);
}
You can simply try
data.forEach(x => x.replace("ABC", "'"));