C
C#6mo ago
twistw00d

-1 in array?

I was using Array, and I find a code like that. The goal is to omit the periods and print the sentences line by line. mystring[] = mystrings[2](“I like pizza.I like salad.”, “I like three of them.”) … while (periodLocation ! = -1) … I don’t know why or how it can has a value as -1…. doesn’t the location start from 0? this is from Microsoft Learn and I didn’t find any tips that explains that. If this is confusing, I can copy the whole code here
8 Replies
Buddy
Buddy6mo ago
and periodLocation is? If it uses IndexOf then -1 means it isn't found. Because returning 0 would not make sense since it is a valid index
twistw00d
twistw00dOP6mo ago
the location of the period! it basically asks where the location of the period is to separate the sentences. Thank you!
Buddy
Buddy6mo ago
huh? The only reason would be if they had a method or something that returned -1 if the index wasn't found. Which as previously mentioned IndexOf does.
SWR
SWR6mo ago
Sharing the actual code sample might help. Also yeah, it sounds like it's using the String.IndexOf method, which returns -1 if it cannot find a match to some string pattern
twistw00d
twistw00dOP6mo ago
string[] myStrings = new string[2] { "I like pizza. I like roast chicken. I like salad", "I like all three of the menu choices" }; int stringsCount = myStrings.Length; string myString = ""; int periodLocation = 0; for (int i = 0; i < stringsCount; i++) { myString = myStrings[i]; periodLocation = myString.IndexOf("."); string mySentence; // extract sentences from each string and display them one at a time while (periodLocation != -1) { // first sentence is the string value to the left of the period location mySentence = myString.Remove(periodLocation); // the remainder of myString is the string value to the right of the location myString = myString.Substring(periodLocation + 1); // remove any leading white-space from myString myString = myString.TrimStart(); // update the comma location and increment the counter periodLocation = myString.IndexOf("."); Console.WriteLine(mySentence); } mySentence = myString.Trim(); Console.WriteLine(mySentence); } that was the solution code
Buddy
Buddy6mo ago
So it was using IndexOf Which is what I said.
MODiX
MODiX6mo ago
Buddy
If it uses IndexOf then -1 means it isn't found. Because returning 0 would not make sense since it is a valid index
Quoted by
<@203166497198047232> from #-1 in array? (click here)
React with ❌ to remove this embed.
twistw00d
twistw00dOP6mo ago
yes, so you are right! thank you very much
Want results from more Discord servers?
Add your server