# C# String Methods Cheat Sheet for Real-Time Projects
## IndexOf()
- **Use Case**: Find the position of the first occurrence of a character or substring.
- **Example**: `"John transferred $500"` Find `"transferred"`.
```csharp
int index = log.IndexOf("transferred");
```
- **Returns**: Index of first match or `-1` if not found.
## LastIndexOf()
- **Use Case**: Find the last occurrence useful for file paths, URLs.
- **Example**: `C:\Users\Abhi\file.txt` Get `"file.txt"`.
```csharp
int index = path.LastIndexOf('\');
string filename = path.Substring(index + 1);
```
## Substring()
- **Use Case**: Extract portion of a string from a starting index.
- **Example**: From `"Amount:$89.99"` get `"$89.99"`.
```csharp
int start = order.IndexOf("Amount:") + "Amount:".Length;
string value = order.Substring(start);
```
## IndexOfAny()
- **Use Case**: Find the first match of any char in a group.
- **Example**: Detect invalid input like `@`, `#`, `%`.
```csharp
char[] symbols = { '@', '#', '%' };
int index = input.IndexOfAny(symbols);
```
## Combined Use Case: Support Ticket Parser
```csharp
string msg = "Ticket: [78912] Issue: {Payment Failure} Time: (2024-06-06)";
char[] open = { '[', '{', '(' };
char[] close = { ']', '}', ')' };
int closePos = 0;
while (true)
int openPos = msg.IndexOfAny(open, closePos);
if (openPos == -1) break;
char openSym = msg[openPos];
char closeSym = close[Array.IndexOf(open, openSym)];
int start = openPos + 1;
int closeIndex = msg.IndexOf(closeSym, start);
Console.WriteLine(msg.Substring(start, closeIndex - start));
closePos = closeIndex + 1;
}
```
## Summary Table
| Method | Purpose | Returns |
|-----------------|-----------------------------------------|--------------|
| `IndexOf()` | First match | Index / -1 |
| `LastIndexOf()` | Last match | Index / -1 |
| `Substring()` | Extract substring | String |
| `IndexOfAny()` | First match from a set of characters | Index / -1 |
---
## Real-World Applications
| Method | Example Scenario |
|--------------|----------------------------------------------------------|
| IndexOf | Find keyword in logs |
| LastIndexOf | Get file name from full path |
| Substring | Extract values like price, timestamp, etc. |
| IndexOfAny | Validate input or parse symbols |