I have a List of Codes (COD_XX) and I need to search each code in a text file, and get the index of the line where is located. The first caracter of the line contains the cod.
I've saved all the lines in a List
var fileLines = File.ReadAllLines(filePath);
List<string> fileItems = new List<string>(fileLines);
foreach (string param in lstCodes)
{
int idx = fileItems.FindIndex(m => m.Substring(0,6) == param)
}
But this expression is not working :( How should I writte it?
Thank you in advanced for your help.
Your code works fine if you put ; after fileItems.FindIndex(...)
But m.Substring(0,6) could throw an exception if m is shorter than 6.
You should use String.StartsWith method.
foreach (string param in lstCodes)
{
int idx = fileItems.FindIndex(m => m.StartsWith(param));
}
Related
I have an ArrayList and want to assign its elements to an array. I can do it using classic old java code:
List<String> list = new ArrayList<String>();
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
String[] optionCode = new String[4];
// Before Java 7
System.out.println("Before Java 7:");
for (int i = 0; i < list.size(); i++) {
optionCode[i] = list.get(i);
}
for (int i = 0; i < optionCode.length; i++) {
System.out.println("Element " + i + " is: " + optionCode[i]);
}
Now I want to use new java 8 features: forEach and lambda method:
list.stream().forEach(i -> {
optionCode[i] = i;
System.out.println(i);
});
It complains: Type mismatch: cannot convert from String to int
How can I fix it?
You may try using the stream toArray() method here:
String[] optionCode = list.stream().toArray(String[]::new);
System.out.println(Arrays.toString(optionCode));
This prints:
[Mango, Apple, Banana, Grapes]
Tim Biegeleisen already suggested the solution to your problem.
The reason, however, that it doesn't work, is that you are trying to access both the index and the element at that index. With forEach, you don't have access to the index.
If you really need to use the index sometime (because, for example, you want to filter out the element at index n), you could use IntStream:
IntStream.range(0, list.size())
.filter(i -> i != n)
.mapToObj(i -> list.get(i)) // Or mapToObj(List::get)
.toArray(String[]::new);
Here is an alternative solution without using forEach.
String[] optionCode = list.toArray(n -> new String[n]);
I have a json array called "names". I want to prevent repeating the same name by searching it before it is entered on the array.
I find this code, but i need also to run the function enterName if the name is not repeated.
Thnaks
var name = "TEST";
for (var i = 0; i < config.names.length; i++){
if (config.names[i] == name){
console.log("name repeated");
}
}
Try this
if (!config.names.find(p=>p===name))
enterName(name);
Using ES7
const name = "TEST";
if (!config.names.includes(name)) {
enterName(name);
}
I need your help.
I made an apex class which is giving output like (1,i,n,d,i,a,,1,2,3) and I would like to show output as a whole string format like(1india 123). I tried many different ways but couldn't get what I actually want.
Here is my apex class:-
public class Assign2{
public void testFunction(String str ,integer num){
integer rem,temp = 0;
integer sumOfDigit = 0;
List<String> stringCharacters = new List<String>();
List<String> inputStr = new List<String>();
stringCharacters = str.split('');
System.debug('stringCharacters::'+stringCharacters);
for(integer i=0; i<stringCharacters.size(); i++){
if(stringCharacters[i].isNumeric()){
temp = Integer.valueOf(stringCharacters[i]);
//System.debug('temp::'+temp);
rem = temp +num;
//System.debug('rem::'+rem);
sumOfDigit = math.mod(rem,10);
//System.debug('sumOfDigit::'+sumOfDigit);
stringCharacters[i] = sumOfDigit+'';
//System.debug('ans::'+stringCharacters);
}
}
System.debug('ans::'+stringCharacters);
}}
and I run the program by giving input:-
Assign2 obj = new Assign2();
obj.testFunction('2india 234',9);
help will be appreciable.
Thank You.
You've used split with empty string as parameter (meaning you want to cut it into 1-character strings). All you have to do is to reverse the process with join.
List<String> characters = new List<String>{'1','i','n','d','i','a',' ','1','2','3'};
String word = String.join(characters, '');
System.debug(word); // "1india 123"
I am trying to create a matching game where one object in the array hitBoxes is matched to one object in the array hitBoxes2. I have tried to convert the instance name into a string and then used the substring method to match the LAST number in the instance name, if its a match they win. Right now I'm getting the error
TypeError: Error #1009: Cannot access a property or method of a null
object reference. at MethodInfo-499()
I'm wondering if anyone can help me. Thanks!
var left:String;
var correct:MovieClip = new Correct;
var isClicked:Boolean = false;
var leftClicked:int = 0;
p3.nextPage.buttonMode = true;
p3.nextPage.addEventListener(MouseEvent.CLICK, nextPage);
function nextPage(MouseEvent):void{
removeChild(p3);
}
var hitBoxes:Array = [p3.a1, p3.a2, p3.a3, p3.a4, p3.a5, p3.a6, p3.a7, p3.a8];
var hitBoxes2:Array = [p3.b1, p3.b2, p3.b3, p3.b4, p3.b5, p3.b6, p3.b7, p3.b8];
for (var h:int = 0; h < hitBoxes.length; h++){
hitBoxes[h].buttonMode = true;
hitBoxes[h].addEventListener(MouseEvent.CLICK, matchingLeft);
}
for (var h2:int = 0; h2 < hitBoxes2.length; h2++){
hitBoxes2[h2].buttonMode = true;
hitBoxes2[h2].addEventListener(MouseEvent.CLICK, matchingRight);
}
function matchingLeft(e:MouseEvent):void{
var left = String(e.currentTarget.name);
isClicked = true;
trace(left);
}
function matchingRight(e:MouseEvent):void{
var right:String = String(e.currentTarget.name);
trace(right);
if(isClicked == true && left.substring(3,3) == right.substring(3,3)){
trace("matched");
}
}
According to your code variable "left" is null at matchingRight method, because matchingLeft uses its local variable with name "left", and top-level "left" still has its default value.
also String.substring method is used incorrectly:
var name:String="p3.a1";
trace(name.substring(3, 3)); // this will always output empty string ""
trace(name.substring(4, 5)); // this will output "1" string
in conclusion I'd advise to use array indices (integers) instead of strings when calculating "matched" condition, substring operation and string comparison are CPU intensive.
I know how to remove duplicates from an array, but what I'm trying to do is prevent an item from ever being added to an array in the first place if it already exists. I'm pulling in data from an xml feed in a loop, and I thought that searching for that values index would work, but no matter what, the index is always -1. Here's my code:
var yearArr:Array = new Array();
for (var i=0;i<numCovers;i++){
var coverRef = xmlObj.cover[i];
var coverClip:MovieClip = new MovieClip();
coverClip.year = coverRef.#year;
if (yearArr.indexOf(coverClip.year === -1)){
yearArr.push (coverClip.year);
}
}
Maybe I'm misunderstanding the indexOf function, but I thought it was supposed to return -1 if a value did not exist in an array. What am I doing wrong?
Here's the solution I came up with:
var yearArr:Array = new Array();
for (var i=0;i<numCovers;i++){
var coverRef = xmlObj.cover[i];
var coverClip:MovieClip = new MovieClip();
coverYear = coverRef.#year;
addCoverYear(coverYear);
}
function addCoverYear(coverYear:int):void {
if (yearArr.indexOf(coverYear) == -1){
yearArr.push(coverYear);
}
}
you can reduce an array by passing everything to a dictionary, which will automatically remove redundancies. then pass the dictionary back as a new array.
//Reduce Array
private function reduceArray(array:Array):Array
{
var dictionary:Dictionary = new Dictionary();
for each (var element:String in array)
dictionary[element] = true;
var result:Array = new Array();
for (var key:String in dictionary)
result.push(key);
dictionary = null;
return result;
}
Your code is almost fine. The problem is that an E4X property .#year is not a literal string (I'm not sure right now, but I believe it's an XMLList object). That's why the indexOf call will keep returning -1, because it is looking for a duplicate of that object, not a string. E4X will convert it to a string as soon as you put it somewhere where only strings can go, but until that time it is something else.
If you rewrite your code like this, it should work right away:
var yearArr:Array = new Array();
for each (var coverRef : XML in xmlObj.cover){
var year : String = coverRef.#year; // force the property to be a string
if (yearArr.indexOf(year) < 0){
yearArr.push (year);
}
}
There were also a few other optimizations you could do to your code. The new MovieClip() part wasn't used, not all variables were strongly typed and by using a for each loop, you can state much clearer what objects you're looping through.
Here is what you could do, if for example, you have an array of strings.
var ItemList:Array = new Array();
for each(var Item:String in UseYourXMLFeed)
{
if(ItemList.indexOf(Item) == -1)
{
ItemList.push(Item);
}
}
Edit:
Anyways, your real answer is in the comment by Sam.