2011-12-23 87 views
-1

如何從包含「I」和「P」之間的文件名「I1P706.jpg」獲取值,因此在這種情況下應該是「1」? 一般該值的長度可以超過1 sumbol如何從字符串名稱獲取值?

+0

將它始終處於那個位置? – 2011-12-23 11:09:44

+0

string [1] ........... – 2011-12-23 11:10:40

+0

你試過了什麼?它只會是1位數嗎?總是在'I'和'P'之間?這些將始終在字符串的開頭嗎?你需要什麼數據類型作爲結果?一個字符串?詮釋?還有別的嗎? – Oded 2011-12-23 11:10:41

回答

2

獲得的I和P指標,然後得到開始iIndex的子(可能需要+ 1)的數我和P(這是P - I)之間的字符。

string myString = "I1P706.jpg" 
int iIndex = myString.IndexOf("I"); 
int pIndex = myString.IndexOf("P"); 

string betweenIAndP = myString.Substring(iIndex + 1, pIndex - iIndex - 1); 
+0

這些都是C#中字符串操作的好方法 – 2011-12-23 11:17:53

+0

爲什麼downvotes? – ThePower 2011-12-23 11:18:03

+2

每個答案都沒有留下評論而從某人下來。這個答案不會返回所需的結果'1''''1'。 – 2011-12-23 11:31:38

-1
string input = "I1P706.jpg"; 
// Get the characters by specifying the limits 
string sub = input.Substring(1,3); 

在這種情況下,輸出將是1P

您也可以你slice功能

PeacefulSlice(1,4)將返回eac

+0

但它的長度可以超過1 – revolutionkpi 2011-12-23 11:11:58

+3

@revolutionkpi - 你沒有這麼說。 – Oded 2011-12-23 11:12:25

2

使用正則表達式:

var r = new Regex(@"I(\d+)P.*"); 
var match = r.Match(input, RegexOptions.IgnoreCase); 
if (match.Success) 
{ 
    int number = 0; // set a default value 
    int.TryParse(match.Groups[1].Value, out number); 
    Console.WriteLine(number); 
} 
1

我猜你想這兩個數字:

using System.Text.RegularExpressions; 

RegEx rx(@"I(\d+)P(\d+)\.jpg"); 

Match m = rx.Match("I1P706.jpg"); 

if(m.Success) 
{ 
    // m.Groups[1].Value contains the first number 
    // m.Groups[2].Value contains the second number 
} 
else 
{ 
    // not found... 
} 
1
var input = "I1P706.jpg"; 
var indexOfI = input.IndexOf("I"); 
var result = input.Substring(indexOfI + 1, input.IndexOf("P") - indexOfI - 1); 
0

這個正則表達式將會給你的所有字符我只是一個P的,忽略案件。這將允許I和P之間的數字增長。

string fileName = "I1222222P706.jpg"; 

Regex r = new Regex(@"(?<=I)(.*?)(?=P)", 
     RegexOptions.Singleline | RegexOptions.IgnoreCase); 

var result = r.Split(fileName).GetValue(1);