您如何区分运算符与知道它不是运算符而是属于字符串?

问题描述 投票:-1回答:2

例如,这是字符串:“您好,这很有挑战性\ n” +“您认为这很容易吗?\ n” + variableName +“ 3 + 4 = 7 \ n”

Dim example = """Hello, this is challenging\n"" + ""you think it is easy?\n"" + variableName + "" 3 + 4 = 7\n"""

我想使用编程方法来安排字符串变为:“您好,这很具有挑战性” +换行符+“您认为这很简单?” +换行符+ variableName +“ 3 + 4 = 7” +换行符

Dim output = """Hello, this is challenging"" + newline + ""you think it is easy?"" + newline + variableName + "" 3 + 4 = 7"" + newline"

如您所见,它涉及到将文本放在引号内所以我在想:1.使用正则表达式获取报价,但是如您所见,我们将省略variableName2.我正在考虑使用+号进行拆分,但是正如您所看到的,“ 3 + 4 = 7”中会出现误报]

告诉我您的想法,这很容易吗?还有其他步骤吗?

vb.net vb.net-2010 vb.net-module
2个回答
0
投票

[标准方法是遍历字符串,计算字符数/翻转表明您是否在字符串中的布尔值

Dim inSideAString = false
Dim quoteChar = "'"c
Dim escapeChar = "\"c
Dim lookForChar  "+"

Dim lastChar = " "c

For i = 0 to theString.Length - 1

  Dim c = theString(i)

  Dim prevChar = If(i > 0, theString(i-1), " "c) 'make it not the escape char

  If c = quoteChar AndAlso prevChar <> escapeChar Then 
    insideAString = (Not insideAString)
    Continue For
  End If

  If c = lookForChar Then
    If insideAString Then 
      Console.Write($"Found a {lookForChar} inside a string at position {i}!")
    Else
      Console.Write($"Found a {lookForChar} outside a string at position {i}!")
    End If
  End If

Next i

0
投票

此单行代码对我有用:

Dim example = """Hello, this is challenging\n"" + ""you think it is easy?\n"" + variableName + "" 3 + 4 = 7\n"""
Dim output = """Hello, this is challenging"" + newline + ""you think it is easy?"" + newline + variableName + "" 3 + 4 = 7"" + newline"

Dim result = String.Join("""", example.Split(""""c).Select(Function(x, n) If(n Mod 2 = 1, x.Replace("\n", """ + newline"), x))).Replace("newline""", "newline")

我得到的与您的输出相同。

© www.soinside.com 2019 - 2024. All rights reserved.