2011-12-23 56 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);